Why am I getting an error \"Attribute value must be constant\". Isn\'t null constant???
@Target(ElementType.TYPE)
@Retention(RetentionPolicy
Class extends Foo> bar() default null;// this doesn't compile
As mentioned, the Java language specification does not allow null values in the annotations defaults.
What I tend to do is to do is to define DEFAULT_VALUE
constants at the top of the annotation definition. Something like:
public @interface MyAnnotation {
public static final String DEFAULT_PREFIX = "__class-name-here__ default";
...
public String prefix() default DEFAULT_PREFIX;
}
Then in my code I do something like:
if (myAnnotation.prefix().equals(MyAnnotation.DEFAULT_PREFIX)) { ... }
In your case with a class, I would just define a marker class. Unfortunately you can't have a constant for this so instead you need to do something like:
public @interface MyAnnotation {
public static Class extends Foo> DEFAULT_BAR = DefaultBar.class;
...
Class extends Foo> bar() default DEFAULT_BAR;
}
Your DefaultFoo
class would just an empty implementation so that the code can do:
if (myAnnotation.bar() == MyAnnotation.DEFAULT_BAR) { ... }
Hope this helps.