【发布时间】:2015-04-29 21:18:52
【问题描述】:
我正在阅读有关 java 注释的信息,出现了一个新的疑问。
在文档中解释 FunctionalInterface 注释类型:
具有一个抽象方法声明的接口称为 功能接口。编译器验证所有带注释的接口 使用@FunctionalInterface 接口真正包含一个和 只有一种抽象方法。如果 使用此注解注解的接口不起作用 接口。使用此注解也是编译时错误 类、注释类型和枚举。功能接口 annotation 类型是一个标记接口。
我做了一些测试,我不需要用这种注释类型标记我的接口。那么,我的问题是:如果每个接口都有一个方法,为什么我需要这个注解?
示例代码
// @FunctionalInterface
interface Wizard {
int spell(String power);
}
class TestLambda {
public static void main(String[] args) {
Wizard gandalf = str -> str.length();
int power = gandalf.spell(args[0]);
System.out.println("The spell length is: " + power+ " points");
}
}
【问题讨论】:
-
您自己发布了答案:“编译器验证所有使用 @FunctionalInterface 注释的接口,这些接口确实包含一个且只有一个抽象方法。”
-
但这是我的疑问?这个注释只是为了那个吗?
-
是的。它确保它实际上是一个功能接口。
标签: java interface annotations