2

While this code happily compiles (with Java 8 / Eclipse Compiler)

public @interface specialized
{
    public Class[] value() default { int.class, long.class, float.class, double.class };
}

Refactoring it to use a constant instead of an array causes an error:

public @interface specialized
{
    public static final Class[] COMMONS = { int.class, long.class, float.class, double.class };

    public Class[] value() default COMMONS;
                                // ^ The value for annotation attribute specialized.value must be a class literal
}

I know that annotation values and -defaults have to be compile-time constants, but although the COMMONS array is technically a compile-time constant, why does this code cause an error? Personally, I think this is extremely counter-intuitive, as it is actually not too much of a pain for the compiler to simply inline this array.

I just realized that they (unsurprisingly) don't work as annotation values either, while they work in both cases in Scala.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Clashsoft
  • 11,553
  • 5
  • 40
  • 79

1 Answers1

3

COMMONS is an array and therefore not a compile-time constant. Only strings and primitives can be part of compile-time constant expressions. You have to consider that a static final array is still mutable.

The default value in the example is not a standard array, it's a special language construct called ElementValueArrayInitializer (JLS 9.7.1).

kapex
  • 28,903
  • 6
  • 107
  • 121
  • But for some reason directly using an array as the annotation value or `default` makes it count as one, so why can't the compiler 'de-reference' the constant field here and inline it's value? This works for `int` or `String` fields as well, so why not for arrays? – Clashsoft May 13 '15 at 20:45
  • 1
    Scala can do this, and even my *little* programming language compiler can do it, so it doesn't seem like a hard thing to do, and the Bytecode also supports it. To me, this seems like either a compiler bug or, more realistically, an error in the spec. – Clashsoft May 13 '15 at 20:51
  • @Clashsoft well, I suggest to submit a bug [here](http://bugreport.java.com/). As far as this site concerns, your question is solved with this answer. – Luiggi Mendoza May 13 '15 at 20:52
  • Thanks, I have submitted it as a Requested javac Feature. Case closed. – Clashsoft May 13 '15 at 21:12