Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface SomeInterface {     Class<? extends Foo> bar() default null;// this doesn't compile } 
like image 601
ripper234 Avatar asked Jul 24 '09 14:07

ripper234


2 Answers

I don't know why, but the JLS is very clear:

 Discussion   Note that null is not a legal element value for any element type.  

And the definition of a default element is:

     DefaultValue:          default ElementValue 

Unfortunately I keep finding that the new language features (Enums and now Annotations) have very unhelpful compiler error messages when you don't meet the language spec.

EDIT: A little googleing found the following in the JSR-308, where they argue for allowing nulls in this situation:

We note some possible objections to the proposal.

The proposal doesn't make anything possible that was not possible before.

The programmer-defined special value provides better documentation than null, which might mean “none”, “uninitialized”, null itself, etc.

The proposal is more error-prone. It's much easier to forget checking against null than to forget checking for an explicit value.

The proposal may make the standard idiom more verbose. Currently only the users of an annotation need to check for its special values. With the proposal, many tools that process annotations will have to check whether a field's value is null lest they throw a null pointer exception.

I think only the last two points are relevant to "why not do it in the first place." The last point certainly brings up a good point - an annotation processor never has to be concerned that they will get a null on an annotation value. I tend to see that as more the job of annotation processors and other such framework code to have to do that kind of check to make the developers code clearer rather than the other way around, but it would certainly make it hard to justify changing it.

like image 195
Yishai Avatar answered Oct 02 '22 05:10

Yishai


Try this

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface SomeInterface {     Class bar() default void.class; } 

It does not require a new class and it is already a keyword in Java that means nothing.

like image 42
Logan Murphy Avatar answered Oct 02 '22 04:10

Logan Murphy