- 相關(guān)推薦
Java8自定義帶泛型的函數(shù)式接口
導(dǎo)語:Java是一門面向?qū)ο缶幊陶Z言,不僅吸收了C++語言的各種優(yōu)點(diǎn),還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強(qiáng)大和簡單易用兩個(gè)特征。下面我們來看看Java8自定義帶泛型的函數(shù)式接口,希望對(duì)大家有所幫助。
Java8自定義帶泛型的函數(shù)式接口,今天寫程序,用的是Java8的特性,Lamda表達(dá)式。大家都應(yīng)該知道,實(shí)際上它就是一個(gè)接口的實(shí)現(xiàn),像是匿名內(nèi)部類一樣。它是有規(guī)則的,只能實(shí)現(xiàn)函數(shù)式接口,什么函數(shù)式接口,就自己百度吧。
我有個(gè)需求,就是需要寫個(gè)公共方法,其中有個(gè)參數(shù)是對(duì)應(yīng)的實(shí)體,也就是說,我這個(gè)參數(shù)可以接收任何實(shí)體,怎么辦呢??
于是想到了泛型,先看我原來是怎么寫的:
1 2 3 4 5 6 7 | @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> |
注意我標(biāo)紅的地方,使用了泛型。在看我調(diào)用的時(shí)候:
1 | CommonResponseConvert response = <u>(datalist,req,cls,res) -></u> {} |
標(biāo)紅的地方一直報(bào)錯(cuò),Illegal lambda expression: Method entityResponse of type CommonResponseConvert is generic 。
于是,我習(xí)慣性的去網(wǎng)上找答案,但很遺憾--------也不知道大家是不是吝嗇于自己的知識(shí),不愿意外漏。結(jié)果導(dǎo)致我一無所獲。
后來中午吃完飯回來,腦補(bǔ)了下。能不能找個(gè)已經(jīng)寫好的接口模仿下呢??當(dāng)然可以了。。。。。?丛创a:
1 2 3 4 5 6 7 8 9 10 11 | 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); }</s,> |
如果這時(shí)候還有人想問我怎么查看源碼,那我可就要打人了!自己百度去吧。
看到了吧,他是在接口的名稱上定義的,那我也模仿下吧,立刻改代碼:
1 2 3 4 5 6 | @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> |
標(biāo)紅的是已加的泛型。再看看調(diào)用:
1 | CommonResponseConvert<t> response = (datalist,req,t,res) -> {}</t> |
這時(shí)候已經(jīng)不報(bào)錯(cuò)了,可以完成接下來的工作了。
結(jié)尾:新東西出來多少會(huì)有些不適應(yīng),希望大家能夠克服困難,不要怕,我始終堅(jiān)持一個(gè)道理---------技術(shù),不是你不會(huì);也是不特別難。而是因?yàn)槟悴⒉皇煜ざ选?/p>
所以,大家只要堅(jiān)持,熟能生巧,一切自然迎刃而解。
【Java8自定義帶泛型的函數(shù)式接口】相關(guān)文章:
java泛型方法04-02
講解Java的泛型07-13
Java的泛型擦除和運(yùn)行時(shí)泛型信息獲取04-29
PHP分頁自定義函數(shù)04-02
C語言自定義函數(shù)08-09
java泛型方法推薦05-25
Java泛型是什么05-03
java編譯器的泛型08-09
初步理解Java的泛型特性分享05-17