Can Annotation implement interfaces?
Is there any possibility implement interface in annotation? Something like:
public @inter开发者_如何学编程face NotNull implements LevelInterface {
ValidationLevel level();
};
No, the compiler says:
Annotation type declaration cannot have explicit superinterfaces
You cannot extend either:
Annotation type declaration cannot have an explicit superclass
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)
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:
public enum LevelEnum implements LevelInterface {
DEFAULT {
public ValidationLevel level() {
// SNIP (your code)
}
};
}
public @interface NotNull {
LevelEnum level() default LevelEnum.DEFAULT;
}
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;
}
精彩评论