当前位置:学者斋 >

计算机 >java语言 >

Java8自定义带泛型的函数式接口

Java8自定义带泛型的函数式接口

导语:Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。下面我们来看看Java8自定义带泛型的函数式接口,希望对大家有所帮助。

Java8自定义带泛型的函数式接口

Java8自定义带泛型的'函数式接口,今天写程序,用的是Java8的特性,Lamda表达式。大家都应该知道,实际上它就是一个接口的实现,像是匿名内部类一样。它是有规则的,只能实现函数式接口,什么函数式接口,就自己百度吧。

我有个需求,就是需要写个公共方法,其中有个参数是对应的实体,也就是说,我这个参数可以接收任何实体,怎么办呢??

于是想到了泛型,先看我原来是怎么写的:

1234567@FunctionalInterface public interface CommonResponseConvert { public <t> DataResponse entityResponse(List<map<string,string>> listMapData, HttpServletRequest request,<u>T t</u>,int result)throws Exception; } </map<string,string></t>

注意我标红的地方,使用了泛型。在看我调用的时候:

1CommonResponseConvert response = <u>(datalist,req,cls,res) -></u> {}

标红的地方一直报错,Illegal lambda expression: Method entityResponse of type CommonResponseConvert is generic 。

于是,我习惯性的去网上找答案,但很遗憾--------也不知道大家是不是吝啬于自己的知识,不愿意外漏。结果导致我一无所获。

后来中午吃完饭回来,脑补了下。能不能找个已经写好的接口模仿下呢??当然可以了。。。。。。看源码:

1234567891011public interface Converter<s, t=""> { /** * Convert the source object of type {@code S} to target type {@code T}. * @param source the source object to convert, which must be an instance of {@code S} (never {@code null}) * @return the converted object, which must be an instance of {@code T} (potentially {@code null}) * @throws IllegalArgumentException if the source cannot be converted to the desired target type */ T convert(S source); }</s,>

如果这时候还有人想问我怎么查看源码,那我可就要打人了!自己百度去吧。

看到了吧,他是在接口的名称上定义的,那我也模仿下吧,立刻改代码:

123456@FunctionalInterface public interface CommonResponseConvert<t> { public DataResponse entityResponse(List<map<string,string>> listMapData, HttpServletRequest request,T t,int result)throws Exception; }</map<string,string></t>

标红的是已加的泛型。再看看调用:

1CommonResponseConvert<t> response = (datalist,req,t,res) -> {}</t>

这时候已经不报错了,可以完成接下来的工作了。

结尾:新东西出来多少会有些不适应,希望大家能够克服困难,不要怕,我始终坚持一个道理---------技术,不是你不会;也是不特别难。而是因为你并不熟悉而已。

所以,大家只要坚持,熟能生巧,一切自然迎刃而解。

  • 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/px5n0.html