Lambda要实现的内容,在其他方法里已经有相同的内容,再写一遍就显得冗余,便可以直接引用该方法。
public class TestJava {
public static void main(String[] args) {
//这里Lambda重写的内容和AAA类中getSum()方法的内容是一样的,重写已有的内容显得冗余
show(ints -> {
int x = 0;
for (int num : ints) {
x += num;
}
System.out.println(x); //打印:15
});
//换成方法引用
show(AAA::getSum); 打印:15
}
public static void show( Consumer<int[]> consumer) {
int[] arr = {1, 2, 3, 4, 5};
consumer.accept(arr);
}
}
class AAA {
public static void getSum(int[] arr) {
int x = 0;
for (int num : arr) {
x += num;
}
System.out.println(x);
}
}
常见引用方式
①被引用方法的参数要和接口中抽象方法的参数一样
②当接口中抽象方法有返回值时,被引用的方法也要有相同类型的返回值
实例方法引用 | instance :: method | 对象 :: 成员方法 |
class :: method | 类名 :: (对象的)成员方法 | |
静态方法引用 | class :: staticMethod | 类名 :: 静态方法 |
构造方法引用 | class :: new | 类名 :: 构造方法 |
type[ ] :: new | 数组 :: 构造方法(数组也是Object子类也有构造) |
public class TestJava {
public static void main(String[] args) {
Date now = new Date();
//对象 :: 成员方法
Supplier<Long> s1 = () -> now.getTime();
Supplier<Long> s2 = now::getTime;
//类名 :: 实例的成员方法
Function<String, Integer> f1 = str -> str.length();
Function<String, Integer> f2 = String::length; //实际是第一个参数调用的成员方法(第二个参数是返回值类型)
BiFunction<String, Integer, String> b1 = ((str, beginIndex) -> str.substring(beginIndex));
BiFunction<String, Integer, String> b2 = String::substring; //实际是第一个参数调用成员方法把第二个参数传进去(第三个参数是返回值类型)
//类名 :: 静态方法
Supplier<Long> s3 = () -> System.currentTimeMillis();
Supplier<Long> s4 = System::currentTimeMillis;
//类名 :: 构造函数
Supplier<AAA> s5 = () -> new AAA();
Supplier<AAA> s6 = AAA::new;
BiFunction<String,Integer,AAA> b3 = (name,age) -> new AAA(name,age);
BiFunction<String,Integer,AAA> b4 = AAA::new; //看似和上面s6无参构造调用的是一样,真正识别是在调用apply()的时候看参数
//数组 :: 构造函数
Function<Integer,int[]> f3 = length -> new int[length];
Function<Integer,int[]> f4 = int[]::new;
int[] ints = f4.apply(5); //长度为5,元素全是0
}
}
class AAA {
public AAA() {
System.out.println("AAA的无参构造");
}
public AAA(String name, int age) {
System.out.println("AAA的有参构造:" + name + age);
}
}