自定义函数式接口需确保仅含一个抽象方法,可使用@FunctionalInterface注解;1. 定义如MyFunction包含apply方法;2. 可添加默认和静态方法,如MyPredicate的and和isNotEmpty;3. 通过Lambda实现,如converter和notEmpty;4. 注意单一抽象方法原则、注解使用、避免盲目继承及合理应用泛型。
在Java中,自定义函数式接口其实很简单。只要一个接口只包含一个抽象方法,它就是函数式接口。你可以使用 @FunctionalInterface 注解来显式声明,这样编译器会帮你检查是否符合函数式接口的规范。
创建一个只含有一个抽象方法的接口:
@FunctionalInterface public interface MyFunction{ R apply(T t); }
这个接口类似于JDK自带的 java.util.function.Function,表示接收一个参数并返回结果的函数。
函数式接口可以有多个默认方法或静态方法,但只能有一个抽象方法:
@FunctionalInterface public interface MyPredicate{ boolean test(T t); default MyPredicate and(MyPredicate other) { return x -> this.test(x) && other.test(x); } static MyPredicate
isNotEmpty() { return s -> s != null && !s.isEmpty(); } }
上面的例子中,test 是唯一的抽象方法,and 是默认方法,isNotEmpty 是静态方法,完全合法。
定义好之后,可以用Lambda表达式或方法引用去实现:
MyFunctionconverter = num -> "Number: " + num; System.out.println(converter.apply(5)); // 输出:Number: 5 MyPredicate notEmpty = s -> s != null && !s.isEmpty(); System.out.println(notEmpty.test("hello")); // true
基本上就这些。自定义函数式接口的关键是“单一抽象方法”,配合Lambda使用非常方便。不复杂但容易忽略细节。