问题
I have an annotation I'm attempting to define that takes a Class parameter. I would like to ensure that the Class provided extends a specific interface. So I came up with...
public @interface Tag {
Class<? extends ITagStyle> style() default NoStyle.class
}
public class NoStyle implements ITagStyle {
...
}
However I get a compile error of "incompatible types".
I'm assuming this is because NoStyle.class
is returning Class
instead of Class<NoStyle>
. In the JLS for Java SE 5 & 7 (couldn't find 6, I'm using 6) it specifically says that "void.class" would return "Class". SEE JLS Class literals: http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.8.2
Is there anyway to do this at compile time? If not I'm guessing the workround is to check the value of style at runtime to ensure it extends ITagStyle :'(
RESOLUTION: JDeveloper has a bug in their "in process" compiler. Checking "out of process" or using JDK7u3 corrects the compile error.
回答1:
This works, so either you are missing something obvious or your error is not related to what you are showing us:
public class Test {
public interface ITagStyle {
}
public @interface Tag {
Class<? extends ITagStyle> style() default NoStyle.class;
}
public class NoStyle implements ITagStyle {
}
public class SomeStyle implements ITagStyle {
}
@Tag(style = SomeStyle.class)
public static void main(String[] args) {
}
}
This has been tested on JDK 1.6.0_26
来源:https://stackoverflow.com/questions/9940610/how-do-you-ensure-a-class-annotation-parameter-extends-an-interface-at-compile-t