title: How to supply Enum value to an annotation from a Constant in Java
body: <p>I'm unable to use an Enum taken from a Constant as a parameter in an annotation. I get this compilation error: "The value for annotation attribute [attribute] must be an enum constant expression".</p>
  
  <p>This is a simplified version of the code for the Enum:</p>
  
  <pre><code>public enum MyEnum {
      APPLE, ORANGE
  }
  </code></pre>
  
  <p>For the Annotation:</p>
  
  <pre><code>@Retention(RetentionPolicy.RUNTIME)
  @Target({ ElementType.METHOD })
  public @interface MyAnnotation {
      String theString();
  
      int theInt();
  
      MyEnum theEnum();
  }
  </code></pre>
  
  <p>And the class:</p>
  
  <pre><code>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() {
  
      }
  
  }
  </code></pre>
  
  <p>The error shows up only in "theEnum = MYENUM_CONSTANT" over methodB. String and int constants are ok with the compiler, the Enum constant is not, even though it's the exact same value as the one over methodA. Looks to me like this is a missing feature in the compiler, because all three are obviously constants. There are no method calls, no strange use of classes, etc.</p>
  
  <p>What I want to achieve is:</p>
  
  <ul>
  <li>To use the MYENUM_CONSTANT in both the annotation and later in the code.</li>
  <li>To stay type safe.</li>
  </ul>
  
  <p>Any way to achieve these goals would be fine.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Thanks all. As you say, it cannot be done. The JLS should be updated. I decided to forget about enums in annotations this time, and use regular int constants. As long as the int is assigned from a named constant, the values are bounded and it's "sort of" type safe.</p>
  
  <p>It looks like this:</p>
  
  <pre><code>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() {
  ...
  </code></pre>
  
  <p>And I can use MYENUMSIMUL_CONSTANT anywhere else in the code.</p>