JAVA 8 '::' 關(guān)鍵字


Java 8 中我們可以通過 :: 關(guān)鍵字來訪問類的構(gòu)造方法,對象方法,靜態(tài)方法

先定義一個接口,因?yàn)楸仨氁?code>@FunctionalInterface修飾,否則編譯錯誤(The target type of this expression must be a functional interface)

@FunctionalInterface
public interface Functional<T,F> {
    T convert(F form);
}
public class FunctionalTest {
    FunctionalTest() {
    }
    FunctionalTest(String something) {
        System.out.println(something);
    }
    public static String methodA(String str) {
        return str;
    }
    public String methodB(String str) {
        return str;
    }
    public static void main(String[] args) {
        // 獲取靜態(tài)方法
        Functional<String, String> convertA = FunctionalTest::methodA;
        String convertedA = convertA.convert("test");
        // 獲取對象方法
        Functional<String, String> convertB = new FunctionalTest()::methodB;
        String convertedB = convertB.convert("test");
        // 獲取構(gòu)造方法
        Functional<FunctionalTest, String> convertC = FunctionalTest::new;
        FunctionalTest convertedCstru  = convertC.convert("test");
    }

::符號相當(dāng)于實(shí)現(xiàn)接口的一種手段,通過::可以將某個類的方法變?yōu)镕unctionl接口的實(shí)現(xiàn)類,但是類方法和接口方法的參數(shù)和返回類型一致,@FunctionalInterface標(biāo)記的接口只能有一個可實(shí)現(xiàn)方法,這樣才能保證將對象方法對應(yīng)到接口方法上,例如 Runnable接口被@FunctionalInterface標(biāo)記,它只有一個 Run 方法?。?!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容