版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013379717/article/details/89634880
一、说明
方法引用使用一对冒号 :: 标识;通过方法的名字来指向一个方法;是函数式接口的另一种书写方式
通过方法引用,可以将方法的引用赋值给一个Function变量;Lambda表达式一般用于自己提供方法体,而方法引用一般直接引用现成的方法
二、示例
- 1、静态方法引用
/**
* 方法无参,有返回
*/
Supplier<Double> supplierD = Math::random;
System.out.println(supplierD.get());
/**
* 方法单参,有返回
*/
Function<String, Integer> fun = Integer::parseInt;
Integer value = fun.apply("123");
System.out.println(value);
- 2、动态方法引用
/**
* 方法无参,有返回
*/
Supplier<String> supplierS = str::toUpperCase;
System.out.println(supplierS.get());
/**
* 方法单参,有返回
*/
Function<Integer, String> functionS = str::substring;
System.out.println(functionS.apply(2));
/**
* 方法单参,无返回
*/
Person p = new Person();
Consumer<String> consumerP = p::setName;
consumerP.accept("张三");
System.out.println(p);
- 3、构造方法引用
/**
* 方法无参
*/
Supplier<Person> supplierP = Person::new;
System.out.println(supplierP.get());
/**
* 方法二参
*/
BiFunction<Integer, String, Person> bifunctionP = Person::new;
System.out.println(bifunctionP.apply(1, "张三"));
/**
* 方法三参 (Jdk没有内置支持该模式的函数式接口,需要自定义,见附录)
*/
CustomFunction<Integer, String, String, Person> customFunctionP = Person::new;
System.out.println(customFunctionP.apply(1, "张三", "广州"));
三、附录
- 1、Person 定义
public class Person {
private Integer id;
private String name;
private String address;
public Person() {
}
public Person(Integer id) {
super();
this.id = id;
}
public Person(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Person(Integer id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
getter / setter ...
toString ...
}
- 2、自定义函数式接口
/**
* 泛型接口:接收 三个类型的参数,返回另一个类型的结果
*/
public interface CustomFunction<T,B,A,R> {
R apply(T t, B b, A a);
}
/**
* 指定类型接口: 接收 用户、商品、地址,返回订单
*/
public interface CustomFunction {
Order apply(User user, Goods goods, Address address);
}