简体   繁体   中英

Annotation definition throwing error: incompatible types: int[] cannot be converted to int

I have an annotation defined in this way.

    class Lit {
      public static final int[] LIT = {1, 2};
    }

    @interface Buggy {
      int[] vals() default Lit.LIT;
    } 

I am getting this error on compilation error: incompatible types: int[] cannot be converted to int .

while this compiles fine:

   @interface Buggy {
    int[] vals() default {1, 2};
   } 

What could be the possible reason?

The error message you are getting is not very informative but the actual reason is that annotation defaults must be constant, which is not the case here.

The below example would work because LIT is constant so you can't change its value:

public class Lit {
    public static final int LIT = 1;
}

@interface Buggy {
    int vals() default Lit.LIT;
}

So for primitive types above approach would work, but not for arrays because arrays are mutable, ie, for your case I can modify LIT's values anywhere in the code, like LIT[1] = 5 , and then it won't have the original value.

But if you declare it as

int[] vals() default {1, 2};

it will work because there's no mutable array variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM