I can not use Enum taken from a constant as a parameter in the annotation. I get this compilation error: "The value of the [attribute] annotation attribute must be a constant expression enum."
This is a simplified version of the code for Enum:
public enum MyEnum { APPLE, ORANGE }
For annotation:
@Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) public @interface MyAnnotation { String theString(); int theInt(); MyEnum theEnum(); }
And the class:
public class Sample { public static final String STRING_CONSTANT = "hello"; public static final int INT_CONSTANT = 1; public static final MyEnum MYENUM_CONSTANT = MyEnum.APPLE; @MyAnnotation(theEnum = MyEnum.APPLE, theInt = 1, theString = "hello") public void methodA() { } @MyAnnotation(theEnum = MYENUM_CONSTANT, theInt = INT_CONSTANT, theString = STRING_CONSTANT) public void methodB() { } }
The error appears only in "theEnum = MYENUM_CONSTANT" by method B. String and int constants are in order with the compiler, the constant Enum is not, although this is the same value as the overA method. It seems to me that this is a missing feature in the compiler, because all three are obviously constants. No method calls, weird use of classes, etc.
What I want to achieve:
- To use MYENUM_CONSTANT both in the annotation and later in the code.
- To keep the type of security.
Any way to achieve these goals will be fine.
Edit:
Thanks to everyone. As you say, this is not possible. JLS needs to be updated. This time I decided to forget about the listings in the annotation and use regular int constants. As long as int is assigned from a named constant, values โโare limited and type-safe.
It looks like this:
public interface MyEnumSimulation { public static final int APPLE = 0; public static final int ORANGE = 1; } ... public static final int MYENUMSIMUL_CONSTANT = MyEnumSimulation.APPLE; ... @MyAnnotation(theEnumSimulation = MYENUMSIMUL_CONSTANT, theInt = INT_CONSTANT, theString = STRING_CONSTANT) public void methodB() { ...
And I can use MYENUMSIMUL_CONSTANT somewhere else in the code.
java enums annotations
user1118312 Nov 06 2018-12-12T00: 00Z
source share