Java 8新特性方法引用詳細介紹_java

來源:互聯網
上載者:User

Java 8新特性方法引用

 對於引用來說我們一般都是用在對象,而對象引用的特點是:不同的引用對象可以操作同一塊內容!

  Java 8的方法引用定義了四種格式:

  1. 引用靜態方法     ClassName :: staticMethodName
  2. 引用對象方法:  Object:: methodName
  3. 引用特定類型方法: ClassName :: methodName
  4. 引用構造方法: ClassName  :: new

 靜態方法引用樣本

/** *   靜態方法引用 * @param <P> 引用方法的參數類型 * @param <R> 引用方法的傳回型別 */@FunctionalInterfaceinterface FunStaticRef<P,R>{  public R tranTest(P p);}public static void main(String[] args) {    /*    *  靜態方法引用: public static String valueOf    *   即將String的valueOf() 方法引用為 FunStaticRef#tranTest 方法    */    FunStaticRef<Integer, String> funStaticRef = String::valueOf;    String str = funStaticRef.tranTest(10000);    System.out.println(str.replaceAll("0", "9"));}

對象方法引用樣本

/** *  普通方法引用 * @param <R> 引用方法傳回型別 */@FunctionalInterfaceinterface InstanRef<R>{  public R upperCase();}public static void main(String[] args) {     /*   * 普通方法的引用: public String toUpperCase()   *   */   String str2 = "i see you";   InstanRef<String> instanRef = str2 :: toUpperCase;   System.out.println(instanRef.upperCase());}

特定類型方法引用樣本

  特定方法的引用較為難理解,本身其引用的是普通方法,但是引用的方式卻為: ClassName :: methodName

 /** * 特定方法的引用 * @param <P> */@FunctionalInterfaceinterface SpecificMethodRef<P>{  public int compare(P p1 , P p2);}public static void main(String[] args) {   /*    * 特定方法的引用 public int compareTo(String anotherString)    *  與之前相比,方法引用前不再需要定義對象,而是可以理解為將對象定義在了參數上!    */   SpecificMethodRef<String> specificMethodRef = String :: compareTo;   System.out.println(specificMethodRef.compare("A","B"));   ConstructorRef<Book> constructorRef = Book :: new;   Book book = constructorRef.createObject("Java",100.25);   System.out.println(book);}

構造方法引用樣本 

class Book{  private String title;  private double price;  public Book() {  }  public Book(String title,double price){    this.price = price;    this.title = title;  }  @Override  public String toString() {    return "Book{" +"title='" + title + '\'' +", price=" + price +'}';  }}public static void main(String[] args) {  /*   * 構造方法引用   */  ConstructorRef<Book> constructorRef = Book :: new;  Book book = constructorRef.createObject("Java",100.25);  System.out.println(book);}

     總的來說Java 8一些新的特性在目前做的項目中還未大量使用,但是學習一下,到時也不至於看到這種Java 8新特性的代碼而不知所錯!

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.