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

来源:互联网 发布:农村淘宝服务站查询 编辑:程序博客网 时间:2024/06/10 16:32

我跟大家一样,对于Java8也是初学者了,所以这里不分技术高低,只凭悟性。

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

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

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

@FunctionalInterfacepublic interface CommonResponseConvert {public <T> DataResponse entityResponse(List<Map<String,String>> listMapData,HttpServletRequest request,T t,int result)throws Exception;}


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

CommonResponseConvert response = (datalist,req,cls,res) -> {}


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

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

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


public 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);}

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


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


@FunctionalInterfacepublic interface CommonResponseConvert<T> {public DataResponse entityResponse(List<Map<String,String>> listMapData,HttpServletRequest request,T t,int result)throws Exception;}

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

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

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


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

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



原创粉丝点击