糯米文學吧

位置:首頁 > 計算機 > java語言

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>

這時候已經不報錯了,可以完成接下來的工作了。

結尾:新東西出來多少會有些不適應,希望大家能夠克服困難,不要怕,我始終堅持一個道理---------技術,不是你不會;也是不特別難。而是因為你並不熟悉而已。

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