「JDK8」函数式接口@FunctionalInterface
@FunctionalInterface的特点
- 该注解只能标记在"有且仅有一个抽象方法"的接口上,表示函数式接口。
- JDK8接口中的静态方法和默认方法,都不算是抽象方法。
- 接口默认继承java.lang.Object,所以如果接口显示声明覆盖了Object中的方法,那么也不算抽象方法。
- 该注解不是必须的,如果一个接口符合"函数式编程"定义,那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查,如果编写的不是函数式接口,但是加上了@FunctionalInterface 那么编译器会报错。
使用Lambda表达式。一般的格式是 ()->{} ,如果{}里面只有一行代码,则{}可以省略。 (->左边的()表示方法体,如果有形参,则在()中添加形参,->右边{}表示具体逻辑。如果方法体返回值是void,则甚至可以在{}中不写任何逻辑(当然也要结合场景)。返回值如果有值,则需要写具体的逻辑,return处理后的值。
@FunctionalInterface
public interface CustomFunctionInterface {
String printStr(String str1, String str2);
}
有两个抽象方法,则会报错:

代码示例
演示一:请求参数、返回参数均有值的接口
@FunctionalInterface
public interface CustomFunctionInterface {
String printStr(String str1, String str2);
}
代码测试:
@Test
public void test2() {
CustomFunctionInterface customFunctionInterface2 = (str1, str2) -> "hello " + str1 + str2;
String printStr = customFunctionInterface2.printStr("A&", "B");
System.out.println("printStr = " + printStr);
}
控制台输出结果:

演示二:请求参数没有值、返回参数有值的接口
@FunctionalInterface
public interface CustomFunctionInterface {
String printStr();
}
测试代码:
@Test
public void test2() {
CustomFunctionInterface customFunctionInterface2 = () -> "hello world";
String printStr = customFunctionInterface2.printStr();
System.out.println("printStr = " + printStr);
}
控制台输出结果:

演示三:实际项目中可借鉴使用(落地)
@FunctionalInterface
public interface CustomFunctionInterface {
void doSomething();
}
假设现在某个类的某个方法形参为CustomFunctionInterface,如代码所示:
public static void execute(CustomFunctionInterface interface3) {
interface3.doSomething();
}
传统的调用方法 :
@Test
public void test3() {
execute(new CustomFunctionInterface() {
@Override
public void doSomething() {
System.out.println("doSomething...");
}
});
}
通过Lambda表达式改进以上测试代码:
@Test
public void test3() {
execute(() -> System.out.println("doSomething..."));
}
可以发现结果是一致的,代码看起来更加简洁美观。

浙公网安备 33010602011771号