JAVA8新特性——函数式接口
函数式接口
有且只有一个抽象方法的接口被称为函数式接口
自定义函数式接口
@FunctionalInterface注解
① 标记@FunctionalInterface注解
② 标记抽象方法
@FunctionalInterface
public interface MyInterface {
/**
* 抽象方法,无参
* @return 带返回值
*/
String get();
}
调用
public class JavaFunctionInterfaceMain {
public static void main(String[] args) {
String text = "测试";
printText(text, System.out::println);
}
public static void printText(String text, MyInterface myInterface) {
myInterface.get(text);
}
}
// 结果可正常输出
常用的函数式接口
Supplier<T>
供给型接口:无入参,有返回
源码
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
应用实例
考虑有两个方法:
private static final String DEFAULT_KEY = "defaultKey";
public Object getMethod(String key) {
if (!StrUtil.isBlank(key) && key.startsWith("https://")) {
return key;
}
return DEFAULT_KEY;
}
@SuppressWarnings("unchecked")
public <T> T getMethod(String key, Class<T> clazz) {
if (!StrUtil.isBlank(key) && key.startsWith("https://")) {
return clazz.cast(key);
}
return (T) DEFAULT_KEY;
}
两种方法逻辑相同,这样书写比较繁琐,考虑利用supplier函数式接口简化代码:
public Supplier<Object> supplier(String key, Class<?> clazz) {
if (!StrUtil.isBlank(key) && key.startsWith("https://")) {
return null == clazz ? () -> key : () -> clazz.cast(key);
}
return null == clazz ? () -> DEFAULT_KEY :
() -> clazz.cast(DEFAULT_KEY);
}
上述两种方法可重写为:
public Object getMethodBySupplier(String key) {
return supplier(key, null).get();
}
@SuppressWarnings("unchecked")
public <T> T getMethodBySupplier(String key, Class<T> clazz) {
return (T) supplier(key, clazz).get();
}
这样,就利用supplier方法完成了对代码的简化,去除了冗余的代码量。其他函数式接口以后更新~