java Annotation 可以实现接口吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4722354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can Annotation implement interfaces?
提问by Kucera.Jan.CZ
Is there any possibility implement interface in annotation? Something like:
是否有可能在注释中实现接口?就像是:
public @interface NotNull implements LevelInterface {
ValidationLevel level();
};
采纳答案by Thilo
No, the compiler says:
不,编译器说:
Annotation type declaration cannot have explicit superinterfaces
注解类型声明不能有显式的超接口
You cannot extend either:
您不能扩展:
Annotation type declaration cannot have an explicit superclass
注解类型声明不能有显式超类
回答by Sean Patrick Floyd
No, an annotation can not have super-interfaces*(although interfaces can extend from an annotation, and classes can implement an annotation, both of which is an awful practice imho)
不,注解不能有超级接口*(尽管接口可以从注解扩展,类可以实现注解,恕我直言,这两种做法都是糟糕的做法)
[*] The funny thing is: I can't find any document that explicitly says so, except the java compiler output (neither the Sun Java Tutorial, nor the Java 1.5 Annotations specification)
[*] 有趣的是:我找不到任何明确说明的文档,除了 java 编译器输出(既不是Sun Java 教程,也不是Java 1.5 注释规范)
回答by sfussenegger
No, you can not (as said in my comment). You may use delegation though (as said by AlexR). However, you'll have to use an enum:
不,你不能(如我的评论中所说)。您可以使用委托(如 AlexR 所说)。但是,您必须使用枚举:
public enum LevelEnum implements LevelInterface {
DEFAULT {
public ValidationLevel level() {
// SNIP (your code)
}
};
}
public @interface NotNull {
LevelEnum level() default LevelEnum.DEFAULT;
}
回答by AlexR
Short answer is No (exactly as Thilo said).
简短的回答是否定的(正如蒂洛所说)。
Long answer is if you really wish such functionality you can use delegation: annotation can hold as many as you wish fields that implement as many as you want interfaces. Please see the following example:
长的答案是,如果您真的希望这样的功能,您可以使用委托:注释可以包含任意数量的字段,实现任意数量的接口。请看下面的例子:
public interface LevelInterface {
public int level();
}
public static LevelInterface foo = new LevelInterface() {
@Override
public int level() {
return 123;
}
};
public @interface NotNull {
LevelInterface level = foo;
}