一、函数式接口定义
1.有且仅有一个抽象方法的接口
2.满足@FuncaionalInterface注解约束(有没有注解都可以,加上注解代码更加清晰且不易出错)
3.可用Lambda表达式实现接口
二、函数式接口示例与注意事项
Java API已经给我们提供了多种函数式接口,如Function、Consumer、Supplier、Runnable等接口
下面展示一些 Function
类相关的源码。
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
显然,函数式接口中不只是只有一个抽象类方法,从Function方法中我们可以看到也可以添加default修饰符修饰的方法,或者static方法。
同时,函数式接口还可以重写Object类方法
@FunctionalInterface
public interface TestFunctionalInterface {
void get();
@Override
String toString();
default void test1(){
System.out.println("test1成功执行");
}
static void test2(){
System.out.println("test2成功执行");
}
}
很明显toString方法也是一个抽象类方法,Object类方法的重写并不会与函数式接口冲突,如此我们就可以很轻松地自定义函数式接口了
三、函数式接口实现
通过Lambda表达式可以实现函数式接口,示例代码如下
@Test
public void testFunctionalInterface(){
TestFunctionalInterface test = ()->{System.out.println("函数式接口测试成功...");};
test.get();
test.test1();
TestFunctionalInterface.test2();
}