首页  >  文章  >  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
上一篇:Unboxing in Java下一篇:JSP Usebean