Java 中的方法引用和构造器引用的差异?
方法引用类似于 lambda 表达式,用于引用一个方法,而不调用该方法,而构造器引用用于引用构造器,而不实例化指定的类。方法引用需要一个目标类型,类似于 lambda 表达式。但它们不是提供一个方法的实现,而是引用现有类或对象的一个方法,而构造器引用则为类内的不同构造器提供不同的名称。
语法 - 方法引用
<Class-Name>::<instanceMethodName>
示例
import java.util.*;
public class MethodReferenceTest {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
List<String> selectedNames = new ArrayList<String>();
names.add("Adithya");
names.add("Jai");
names.add("Raja");
names.forEach(selectedNames :: add); // instance method reference
System.out.println("Selected Names:");
selectedNames.forEach(System.out :: println);
}
}输出
Selected Names: Adithya Jai Raja
语法 - 构造器引用
<Class-Name>::new
示例
@FunctionalInterface
interface MyInterface {
public Student get(String str);
}
class Student {
private String str;
public Student(String str) {
this.str = str;
System.out.println("The name of the student is: " + str);
}
}
public class ConstrutorReferenceTest {
public static void main(String[] args) {
MyInterface constructorRef = Student :: new; // constructor reference
constructorRef.get("Adithya");
}
}输出
The name of the student is: Adithya
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP