Can someone explain why String and Class annotation parameters are expected differently? Why does the compiler require literals for Classes, wherby accepting constants for Strin
The Java Language Specification doesn't permit you to use compile-time constants with parameters of type Class
. You can only use class literals.
The JLS has the following to say about suitable parameter values for annotations:
An element type T is commensurate with an element value V if and only if one of the following conditions is true:
- T is an array type E[] and either:
- V is an ElementValueArrayInitializer and each ElementValueInitializer (analogous to a variable initializer in an array initializer) in V is commensurate with E. Or
- V is an ElementValue that is commensurate with T.
- The type of V is assignment compatible (§5.2) with T and, furthermore:
- If T is a primitive type or String, V is a constant expression (§15.28).
- V is not null.
- if T is Class, or an invocation of Class, and V is a class literal (§15.8.2).
- If T is an enum type, and V is an enum constant.
It is a compile-time error if the element type is not commensurate with the ElementValue.
I can't say why this restriction is in the JLS, however.