3

I have enum:

public enum Scope {
    USER, GLOBAL;

    public static final Scope[] TRANSIENT = {};
    public static final Scope[] USER_OVER_GLOBAL = {GLOBAL, USER};
    public static final Scope[] GLOBAL_OVER_USER = {USER, GLOBAL};
}

and annotation:

public @interface Config {
    public Scope[] load() default Scope.GLOBAL_OVER_USER; // Can't use this defval

    public Scope[] save() default Scope.USER;
}

Why I can't use static arrays as default values for annotation's property? My NetBeans 7.3 Beta tell me there is required Scope but found Scope[] - as you can see this not true. Is there a NB's or Java 7 related confusion?

kbec
  • 3,415
  • 3
  • 27
  • 42
  • Are you sure that error is occurring on the line illustrated? Because your code as shown should fail on the line below it. – Perception Nov 13 '12 at 11:51
  • @Perception: this is annotation, so `USER` is treated as `{USER}` and it's not a mistype. Problem is with using static hand-made values for annotation's defaults. – kbec Nov 13 '12 at 12:05

1 Answers1

4

The problem is that the Scope[] GLOBAL_OVER_USER is not all constant. (Yes, the array itself is constant, however you can change the contents of it e.g. GLOBAL_OVER_USER[0] = GLOBAL;.

A workaround is to initiate the array directly in the annotation declaration:

public Scope[] load() default {USER, GLOBAL};
matsev
  • 32,104
  • 16
  • 121
  • 156
  • I know this workaround, but then how to get default value for this annotation property without its instance? – kbec Nov 13 '12 at 12:03
  • Well, you don't have to. By just adding `@Config` (or @Config(save=Scope.GLOBAL) ) the annotation's `load` value will keep it's default value. – matsev Nov 13 '12 at 12:11
  • Of course, but imagine case when you don't annotate field to imply annotation defaults. – kbec Nov 13 '12 at 12:15
  • [There](http://stackoverflow.com/a/613469/854291) is a way for getting annotation's defaults. – kbec Nov 13 '12 at 16:34