Error setting a default null value for an annotation's field

前端 未结 7 1955
渐次进展
渐次进展 2020-11-30 08:20

Why am I getting an error \"Attribute value must be constant\". Isn\'t null constant???

@Target(ElementType.TYPE)
@Retention(RetentionPolicy         


        
7条回答
  •  有刺的猬
    2020-11-30 08:53

    Class 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 DEFAULT_BAR = DefaultBar.class;
        ...
        Class 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.

提交回复
热议问题