首頁  >  文章  >  Java  >  Java 方法參考

Java 方法參考

王林
王林原創
2024-08-30 15:09:10430瀏覽

以下文章提供了 Java 方法參考的概述。在JDK 8中,引入了lambda表達式,可以在一行中建立匿名方法來執行一項操作。但是,在呼叫現有方法時編寫 lambda 表達式時,可以使用方法參考來實作此類操作。這使得存在對現有方法的呼叫的表達式更加緊湊和可讀。此外,在方法參考範圍中,解析運算子(:: )用於將方法名稱與類別名稱分開。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

Java 方法引用的型別

讓我們透過一個例子來看看方法引用的必要性:

代碼:

public class Employee {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDatejoiningDate;
Sex gender;
String emailAddress;
public int getNumberOfYears() {
}
public Calendar getJoiningDate() {
return joiningDate;
}
public static int compareByJoiningDate(Employeea, Employeeb) {
return a.joiningDate.compareTo(b.joiningDate);
}}

如果我們想按 joinDate 對員工清單進行排序意味著誰先加入,那麼我們可以在其中一個子類別中呼叫下面給出的方法。

代碼:

Person[] rosterAsArray = roster.toArray(new Employee[roster.size()]);
class JoiningDateComparator implements Comparator<Employee> {
public int compare(Employeea, Employeeb) {
return a.getJoiningDate().compareTo(b.getJoiningDate());
}
}

因此,我們可以寫一個 lambda 表達式來呼叫上述方法,同時對清單進行排序,以比較 2 位員工的入職日期。

代碼:

Arrays.sort(rosterAsArray,
(a, b) ->Person.compareByAge(a, b)
);

或者我們可以透過以下方式呼叫該方法;兩者俱有相同的含義,為數組中的每對物件呼叫方法。

代碼:

Arrays.sort(rosterAsArray, Person::compareByAge)

JDK 8 中存在以下四種類型的方法引用:

1.靜態方法的引用

使用 :: 運算子來引用靜態方法稱為靜態方法的參考。

文法:

ClassName::MethodName()

工作中:

  • 這裡引用的方法是靜態類型,這意味著不需要類別的實例來呼叫該方法;相反,只有類別名稱就足夠了。
  • 因此,當有人在 lambda 表達式中提及 ClassName::MethodName 時,JRE 會前往該類別以尋找所提到的類別中的靜態方法。由於它是對靜態方法的調用,因此不能在非靜態區塊下提及。

範例:

在下面的範例中,使用 java.util 套件中 bifunction 類別的功能呼叫 Addition 類別的靜態方法 add,其中該方法的參考儲存在 myObj 物件中,並傳遞所需的值作為參數傳遞。

代碼:

import java.util.function.BiFunction;
class Addition{
public static int add(int a, int b){
return a+b;
}
}
public class HelloWorld {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer>myObj = Addition::add;
int res = myObj.apply(30, 5);
System.out.println("Sum of given number is: "+res);
}
}

輸出:

Java 方法參考

2.引用特定物件的實例方法

文法:

object::methodName()

工作中:

  • 在這種類型的參考中,使用類別的物件來引用其實例方法之一。這裡 JRE 檢查傳遞的參數是否與方法宣告中提到的型別相同。
  • 這有助於使用類別的實例方法編寫 lambda 表達式。

範例:

在下面的範例中,使用實例方法的方法參考來呼叫類別 HelloWorld 的 showName 方法。

代碼:

interface MyInterface{
void display();
}
public class HelloWorld {
public void showName(){
System.out.println("Call to method ShowName");
}
public static void main(String[] args) {
HelloWorld obj = new HelloWorld();
MyInterface ref = obj::showName;
ref.display();
}
}

輸出:

Java 方法參考

3.引用特定類型的任意物件的實例方法

文法:

ClassName :: instanceMethodName()

工作中:

  • 這與上面給出的引用類型相同,不同之處在於這裡引用的物件是不斷變化的,這意味著許多物件使用方法引用呼叫相同的方法但類型相同。

範例: 在下面的範例中,我們對陣列中儲存的所有字串呼叫compareToIgnoreCase 方法。因此,這不是一個接一個地傳遞不同的對象,而是使用名冊在單一語句中發生。

代碼:

import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
String[] empArray = { "John", "Jack", "Aditya", "Vishal", "Saurabh", "Amanda", "Daniel"};
Arrays.sort(empArray, String::compareToIgnoreCase);
System.out.println("Sorted list of names of Employees \n");
for(String str: empArray){
System.out.println(str);
}
}
}

輸出:

Java 方法參考

4.引用建構子

文法:

myFunc(roster, HashSet<MyClass>::new);

工作中:

  • 此引用呼叫也是為了呼叫類別的建構子。
  • 為此,在 lambda 表達式中使用「new」關鍵字,以便 JRE 推斷呼叫該特定類別的建構子。

讓我們舉一個 lambda 表達式的範例,該表達式包含對以下方法的調用,並且需要傳遞一個新的 HashSet 建構子。

代碼:

publicstatic<T, MYSRCextends Collection<T>, MYDESTextends Collection<T>>
MYDEST MyMethod(
MYSRC src,
Supplier< MYDEST>dest) {
MYDEST res = collectionFactory.get();
for (T t : src)
{res.add(t);
}
returnres;
}

那麼 lambda 表達式將類似於:

代碼:

Set<myClass>rosterSet = MyMethod(roster, HashSet::new);

這裡 JRE 自動推斷傳遞的參數包含 myClass 類型的對象,或者我們可以使用下面的 lambda 表達式

Set<myClass>rosterSet = transferElements(roster, HashSet<myClass>::new);

Example: In the below example, a constructor of a firstReference class is being called using ‘new’ operator and stored in a reference variable ‘inObj’. This reference variable is then used to refer to the instance methods of this class.

Code:

@FunctionalInterface
interface firstInterface{
firstReference show(String say);
}
class firstReference{
public firstReference(String say){
System.out.print(say);
}
}
public class HelloWorld {
public static void main(String[] args) {
//Method reference to a constructor
firstInterface inObj = firstReference::new;
inObj.show("Let’s begin learning Contructor type method reference");
}
}

Output:

Java 方法參考

Conclusion

Method Reference is a way to make a call to an existing method in lambda expressions being used in the application. This feature has been introduced with JDK 1.8 to make lambda expressions more compact and reuse the existing code. There are four ways to make calls to the methods of the class names as shown above.

以上是Java 方法參考的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:在 Java 中拆箱下一篇:在 Java 中拆箱