一、简介
- Java Supplier是一个功能接口,代表结果的提供者。
- Supplier的功能方法是get()。
- 一个Supplier可以通过lambda表达式、方法引用或默认构造函数来实例化。
- Supplier在Java 8中被引入,属于java.util.function包。
二、源码
@FunctionalInterface
public interface Supplier<T> {
//get()方法不接受任何参数,只返回通用类型的值。
T get();
}
- 我们可以看到在上面的代码中,Supplier有get()方法,可以返回通用类型的值。
- Java还提供了返回特定类型值的Supplier。
- BooleanSupplier返回Boolean数据类型,IntSupplier返回Integer数据类型,LongSupplier返回Long数据类型,DoubleSupplier返回Double数据类型值。
三、使用示例
public class SupplierGet {
public static void main(String[] args) {
supplierTest();
}
public static void supplierTest() {
//使用Lambda表达式实例化Supplier
Supplier<String> supplier = () -> "hello 张三";
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
//输出:supplierTest-->hello 张三
System.out.printf("{%s}-->{%s}%n", methodName, supplier.get());
//使用方法引用实例化Supplier
Supplier<String> supplier2 = User::getNameAndAge;
//输出:supplierTest-->张三今年29了,加油!
System.out.printf("{%s}-->{%s}%n", methodName, supplier2.get());
//使用默认构造函数实例化Supplier
Supplier<User> supplier3 = User::new;
User user = supplier3.get();
//输出:supplierTest-->张三
System.out.printf("{%s}-->{%s}%n", methodName, user.getName());
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public static class User {
public static String getNameAndAge() {
return String.format("{%s}今年{%s}了,加油!", "张三", 29);
}
private String name = "张三";
private int age = 29;
}
}
四、总结
函数式编程应该用在抽象层次高、复用多的场景,而不是单纯业务逻辑的简单使用(反而影响代码的可阅读性)。找到具体场景中的最佳实践才能发挥函数式编程最大优点。