Java 8为函数式接口引入了一个新注解@FunctionalInterface,
- 主要用于编译级错误检查,加上该注解,
- 当你写的接口不符合函数式接口定义的时候,编译器会报错。
-
@FunctionalInterface interface GreetingService { //只有一个抽象方法 void sayMessage(String message); }
所谓的函数式接口,
-
当然首先是一个接口,
-
然后就是在这个接口里面只能有一个抽象方法。
-
函数式接口用途
- 主要用在Lambda表达式和方法引用(实际上也可认为是Lambda表达式)上。
函数式接口里允许定义默认方法
-
@FunctionalInterface interface GreetingService { void sayMessage(String message); default void doSomeMoreWork1() { // Method body } default void doSomeMoreWork2() { // Method body } }
函数式接口里允许定义静态方法
-
@FunctionalInterface interface GreetingService { void sayMessage(String message); static void printHello(){ System.out.println("Hello"); } }
函数式接口里允许定义java.lang.Object里的public方法
-
@FunctionalInterface interface GreetingService { void sayMessage(String message); @Override boolean equals(Object obj); }
JDK中的函数式接口举例
- java.lang.Runnable,
- java.awt.event.ActionListener,
- java.util.Comparator,
- java.util.concurrent.Callable
- java.util.function包下的接口,如Consumer、Predicate、Supplier等