溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2020-11-02 17:10:22 來(lái)源:億速云 閱讀:155 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

JAVA 8 '::' 關(guān)鍵字的用法?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

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

現(xiàn)有一個(gè)類 Something

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() {}
}

如何用 '::' 來(lái)訪問(wèn)類Something中的方法呢?先定義一個(gè)接口,因?yàn)楸仨氁?functional interface 來(lái)接收,否則編譯錯(cuò)誤(The target type of this expression must be a functional interface)

@FunctionalInterface
interface IConvert<F, T> {
  T convert(F form);
}

(@FunctionalInterface 注解要求接口有且只有一個(gè)抽象方法,JDK中有許多類用到該注解,比如 Runnable,它只有一個(gè) Run 方法。)

觀察接口 IConvert,傳參為類型 F,返回類型 T。所以,我們可以這樣訪問(wèn)類Something的方法:

訪問(wèn)靜態(tài)方法

// static methods
IConvert<String, String> convert = Something::startsWith;
String converted = convert.convert("123")

訪問(wèn)對(duì)象方法

// object methods
Something something = new Something();
IConvert<String, String> converter = something::endWith;
String converted = converter.convert("Java");

訪問(wèn)構(gòu)造方法

// 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的那個(gè)“模版”,有傳參類型F以及返回值類型T。比如構(gòu)造方法Something(String something),它傳參為String類型,返回值類型為Something。注解@FunctionalInterface保證了接口有且僅有一個(gè)抽象方法,所以JDK能準(zhǔn)確地匹配到相應(yīng)方法。

關(guān)于JAVA 8 &#039;::&#039; 關(guān)鍵字的用法問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI