方法引用
1 2
| Comparator<Integer> com3 = Integer :: compare; System.out.println(com3.compare(23,21));
|
方法引用可以看作是基于Lambda表达式的进一步刻画
当满足一定条件的情况下,我们还可以使用方法应用或构造器引用替换Lambda表达式
方法引用的格式
类(或对象):: 方法名
函数式接口的抽象方法(重写)a与其内部实现时调用对象的某个方法b的形参列表和返回值类型都相同
可以考虑使用方法b实现对方法a的覆盖。此替换即为方法引用
函数式接口的抽象方法(重写)a与其内部实现时调用类的某个静态方法方法b的形参列表和返回值类型都相同
可以考虑使用方法b实现对方法a的覆盖。此替换即为方法引用
函数式接口的抽象方法(重写)a与其内部实现时调用对象的某个方法b的返回值类型相同
同时,抽象方法a中有n个参数,方法b中有n-1个参数,且抽象方法a的第一个参数作为方法b的调用者,后n-1个参数与方法b的n-1个参数相同。可以考虑使用方法b实现对方法a的覆盖。此替换即为方法引用
注:此方法b是非静态方法,本质上还是使用对象调用。但形式上我们写对象a所在的类
构造器引用
类名 :: new
应用案例
Person类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Person { private int id; private String name; public Person(int id) { this.id = id; } public Person(int id, String name) { this.id = id; this.name = name; } public Person() { } }
|
案例要求:实例化一个Person类的对象,使用构造器引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import org.junit.Test;
import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier;
public class ConstructorTest { @Test public void test() { Supplier<Person> supplier = new Supplier<Person>() { @Override public Person get() { return new Person(); } }; Supplier<Person> supplier1 = Person::new; }
@Test public void test2() { Function<Integer, Person> function = new Function<Integer, Person>() { @Override public Person apply(Integer integer) { return new Person(integer); } }; Function<Integer, Person> function1 = Person::new; }
@Test public void test3() { BiFunction<Integer, String, Person> function = new BiFunction<Integer, String, Person>() { @Override public Person apply(Integer integer, String s) { return new Person(integer, s); } }; BiFunction<Integer, String, Person> biFunction = Person::new; } }
|
**总结:**无论使用何种构造器,最后的格式不变,因类型推断的缘故,构造器参数看的是泛型类型
数组引用
1 2 3 4 5 6 7 8 9 10 11
| public void test4() { Function<Integer, Person[]> function = new Function<Integer, Person[]>() { @Override public Person[] apply(Integer integer) { return new Person[integer]; } }; Function<Integer, Person[]> function1 = Person[]::new; }
|