【发布时间】:2012-10-26 13:24:50
【问题描述】:
我无法使用取自常量的枚举作为注释中的参数。我收到此编译错误:“注释属性 [attribute] 的值必须是枚举常量表达式”。
这是 Enum 代码的简化版本:
public enum MyEnum {
APPLE, ORANGE
}
对于注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface MyAnnotation {
String theString();
int theInt();
MyEnum theEnum();
}
还有班级:
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() {
}
}
该错误仅出现在方法 B 上的“theEnum = MYENUM_CONSTANT”中。编译器可以使用 String 和 int 常量,但 Enum 常量不行,即使它与方法 A 上的值完全相同。在我看来这是编译器中缺少的功能,因为这三个显然都是常量。没有方法调用,没有奇怪的类使用等等。
我想要实现的是:
- 在注释和后面的代码中都使用 MYENUM_CONSTANT。
- 为了保证打字安全。
任何实现这些目标的方法都可以。
编辑:
谢谢大家。正如你所说,这是不可能的。 JLS 应该更新。这次我决定忘记注释中的枚举,并使用常规的 int 常量。只要 int 是从命名常量分配的,值就会有界并且它是“某种”类型安全的。
看起来像这样:
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() {
...
我可以在代码中的任何其他地方使用 MYENUMSIMUL_CONSTANT。
【问题讨论】:
标签: java enums annotations