Java 8 中我們可(kě)以通(tōng)過 `::` 關鍵字來λ∏(lái)訪問(wèn)類的(de)構造方法,對(duì)象方法,靜(≤λjìng)态方法。
現(xiàn)有(yǒu)一(yī)個(gèΩγ™)類 Something:
class Something {
// constructor™ methods
Someth'λφ•ing() {}
Something(String someth®λing) {
System.out.println(something'↓);
}
// stati₽©®c methods
static String$&Ω₩ startsWith(String s) {
≈♦ return String.value∑© Of(s.charAt(0));
}
// object methods
String'λ♠ endWith(String s) {
return Stri★₩ng.valueOf(s.charAt(s.length()-1)β≤Ω®);
}
void endWith(₩←∑) {}
}
如(rú)何用(yòng) ''::'' 來(lái)訪問♣✘™(wèn)類Something中的(de)方法呢(ne)?先定義一 ↑(yī)個(gè)接口,因為(wèi)必≤'∞₩須要(yào)用(yòng) functional i↓φnterface 來(lái)接收,否則編譯錯(cuσβ♥ò)誤(The target type of this expr≠∑↑ession must be a functional interfa™>φce):
@FunctionalInterface
interface IConvert&l♦∞t;F, T> {
T convert(F form);
}
(@FunctionalInterface 注解要 α(yào)求接口有(yǒu)且隻有(yǒu)一(yī)個(gè)抽象方法,JD♠K中有(yǒu)許多(duō)類用(yòng)到(dào)該注解,比 ↓☆如(rú) Runnable,它隻有(yǒu)一(yī)個(gè) Run 方 •法。)
觀察接口 IConvert,傳參為(wèi)類型 F,返回類型 T。所以,我 $₩<們可(kě)以這(zhè)樣訪問(wèn)類Something的(d<®e)方法:
訪問(wèn)靜(jìng)态方法:
// static methods
IConvert<String, StrΩ↕←↔ing> convert = Something::starts"£πWith;
String converted = convert.convert(•₽£ε"123");
訪問(wèn)對(duì)象方法:
// object methods
Something something = new Something()♦↓ ;
IConvert<String, String> convert•∞er = something::endWith;
String converted = converter.conα'vert("Java");
訪問(wèn)構造方法:
// constructor methods
IConvert<String, Something> conve→×≥↑rt = Something::new;
Something something = convert.↔¥¥convert("constructor←> αs");
總結:我們可(kě)以把類Something中的(de)方↓Ω• 法static String startsWith(String s){..ε≠.}、String endWith(String s®≈){...}、Something(String some↕thing){...}看(kàn)作(zuò)<♦÷是(shì)接口IConvert的(de)實現(xφ φiàn),因為(wèi)它們都(dōu)符合接口定義的(de)那(nà)個↓σ∏(gè)“模版”,有(yǒu)傳參類型F以及返回值類型T。比如(rú→$)構造方法Something(Strin ↑≠g something),它傳參為(wèi)String←類型,返回值類型為(wèi)Something。↑β☆λ注解@FunctionalInterfac★≠e保證了(le)接口有(yǒu)且僅有(yǒu)一($¥>yī)個(gè)抽象方法,所以JDK能(n$φéng)準确地(dì)匹配到(dào)相(xiàng)應方法₩±ε。
|