Java8新特性之方法引用、构造器引用、数组引用
一. 方法引用
? 若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用”。(可以理解为方法引用是Lambda表达式的另外一种表现形式)
特别注意:Lambda体中调用方法的参数类型和返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
主要有三种语法格式:
-
对象 :: 实例方法名
Consumerconsumer1 = (x) -> System.out.println(x); consumer1.accept("fjh1"); PrintStream ps = System.out; Consumer consumer2 = ps::println; consumer2.accept("fjh2"); -
类 :: 静态方法名
Comparatorcomparator1 = (x,y) -> { return Integer.compare(x,y); }; Comparator comparator2 = Integer::compare; -
类 :: 实例方法名
参数列表中第一个参数是实例方法的调用者,第二个参数是实例方法的参数时,才可以使用这个语法。
BiPredicate bp = (x,y)-> x.equals(y);
BiPredicate bp2 = String::equals;
二. 构造器引用
语法格式:类名 :: new
调用哪个构造器 取决于接口方法的参数,如本例的get()方法调用无参构造器,apply调用1参对应构造器。
Supplier supplier1 = () -> new Animal();
Supplier supplier2 = Animal::new;
System.out.println(supplier2.get());
Function function1 = (x)-> new Animal(x);
Function function2 = Animal::new;
System.out.println(function2.apply("fjh"));
三. 数组引用
语法格式:Type::new
Function function = (x) -> new String[x];
String[] strs = function.apply(100);
System.out.println(strs.length);
Function function2 = String[]::new;
String[] strs2 = function2.apply(200);
System.out.println(strs2.length);