Java8自定义带泛型的函数式接口,今天写程序,用的是Java8的特性,Lamda表达式。大家都应该知道,实际上它就是一个接口的实现,像是匿名内部类一样。它是有规则的,只能实现函数式接口,什么函数式接口,就自己百度吧。
我有个需求,就是需要写个公共方法,其中有个参数是对应的实体,也就是说,我这个参数可以接收任何实体,怎么办呢??
于是想到了泛型,先看我原来是怎么写的:
@FunctionalInterface public interface CommonResponseConvert { public注意我标红的地方,使用了泛型。在看我调用的时候:DataResponse entityResponse(List<> > 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{ /** * 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); }
看到了吧,他是在接口的名称上定义的,那我也模仿下吧,立刻改代码:
@FunctionalInterface public interface CommonResponseConvert{ public DataResponse entityResponse(List<> > listMapData, HttpServletRequest request,T t,int result)throws Exception; }
CommonResponseConvertresponse = (datalist,req,t,res) -> {}
结尾:新东西出来多少会有些不适应,希望大家能够克服困难,不要怕,我始终坚持一个道理---------技术,不是你不会;也是不特别难。而是因为你并不熟悉而已。
所以,大家只要坚持,熟能生巧,一切自然迎刃而解。