Java 8 中我們可以通過 `::` 關(guān)鍵字來訪問類的構(gòu)造方法,對象方法,靜態(tài)方法。
現(xiàn)有一個類 Something
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class Something { // constructor methods Something() {} Something(String something) { System.out.println(something); } // static methods static String startsWith(String s) { return String.valueOf(s.charAt( 0 )); } // object methods String endWith(String s) { return String.valueOf(s.charAt(s.length()- 1 )); } void endWith() {} } |
如何用 '::' 來訪問類Something中的方法呢?先定義一個接口,因?yàn)楸仨氁?functional interface 來接收,否則編譯錯誤(The target type of this expression must be a functional interface)
1
2
3
4
|
@FunctionalInterface interface IConvert<F, T> { T convert(F form); } |
(@FunctionalInterface 注解要求接口有且只有一個抽象方法,JDK中有許多類用到該注解,比如 Runnable,它只有一個 Run 方法。)
觀察接口 IConvert,傳參為類型 F,返回類型 T。所以,我們可以這樣訪問類Something的方法:
訪問靜態(tài)方法
1
2
3
|
// static methods IConvert<String, String> convert = Something::startsWith; String converted = convert.convert( "123" ) |
訪問對象方法
1
2
3
4
|
// object methods Something something = new Something(); IConvert<String, String> converter = something::endWith; String converted = converter.convert( "Java" ); |
訪問構(gòu)造方法
1
2
3
|
// constructor methods IConvert<String, Something> convert = Something:: new ; Something something = convert.convert( "constructors" ); |
總結(jié)
我們可以把類Something中的方法static String startsWith(String s){...}、String endWith(String s){...}、Something(String something){...}看作是接口IConvert的實(shí)現(xiàn),因?yàn)樗鼈兌挤辖涌诙x的那個“模版”,有傳參類型F以及返回值類型T。比如構(gòu)造方法Something(String something),它傳參為String類型,返回值類型為Something。注解@FunctionalInterface保證了接口有且僅有一個抽象方法,所以JDK能準(zhǔn)確地匹配到相應(yīng)方法。
到此這篇關(guān)于JAVA 8 '::' 關(guān)鍵字的文章就介紹到這了,更多相關(guān)JAVA 8 '::' 關(guān)鍵字內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/kegaofei/article/details/80582356