java枚举常量代表的值_如何在Java中从常量向枚举提供枚举值

我无法使用从常量中获取的枚举作为注释中的参数。我收到此编译错误:“注释属性[attribute]的值必须是枚举常量表达式”。

这是枚举代码的简化版本:

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”中显示。字符串和int常量对于编译器是可以的,但Enum常量不是,即使它的值与methodA上的值完全相同。在我看来,这是编译器中缺少的功能,因为这三个显然都是常量。没有方法调用,没有奇怪的类使用等。

我要实现的是:

要在注释中和代码后面均使用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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值