任意只包含一个抽象方法的接口,我们都可以用来做成lambda表达式。为了让你定义的接口满足要求,你应当在接口前加上@FunctionalInterface 标注。编译器会注意到这个标注,如果你的接口中定义了第二个抽象方法的话,编译器会抛出异常。
举例:
- @FunctionalInterface
- interface Converter<F, T> {
- T convert(F from);
- }
- Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
- Integer converted = converter.convert("123");
- System.out.println(converted); // 123
注意,如果你不写@FunctionalInterface 标注,程序也是正确的。