方法引用和构造器引用
1、方法引用
当要传递给Lambda体的操作已经有实现方法,可以直接使用方法引用(实现抽象方法的列表,必须要和方法引用的方法参数列表一致)
方法引用:使用操作符“::”将方法名和(类或者对象)分割开来。
有下列三种情况:
对象::实例方法
类::实例方法
类::静态方法
代码展示:
package com.chen.test.JAVA8Features; public class MethodRefDemo { public static void main(String[] args) { FunctionGeneric strName = s -> System.out.println(s); strName.fun("Lambda表达式没有使用方法引用");
//方法引用
FunctionGeneric<String> strName2 = System.out::println;
strName2.fun("使用方法引用");
} } 2、构造器引用
本质上:构造器引用和方法引用相识,只是使用了一个new方法
使用说明:函数式接口参数列表和构造器参数列表要一致,该接口返回值类型也是构造器返回值类型
格式:ClassName :: new
代码展示:
package com.chen.test.JAVA8Features; import java.util.function.Function; public class MethodRefDemo { public static void main(String[] args) { //构造器引用 Function<String, Integer> fun1 = (num) -> new Integer(num); Function<String, Integer> fun2 = Integer::new; //数组引用 Function<Integer,Integer[]> fun3 = (num) ->new Integer[num]; Function<Integer,Integer[]> fun4 = Integer[]::new; } }