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

Time:01-05

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?

CodePudding user response:

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, i.e., 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.

  •  Tags:  
  • java
  • Related