作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经编写了自定义注释,并且如果我按如下方式使用它,则工作正常。
@MyAnnotation("sun")
public void getResult(String id){
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
上面的代码工作正常。现在,我不想将“sun”硬编码,而是将其保留在枚举中,如下所示。
public enum WeekDay{
SUNDAY("sun"), MONDAY("mon");
private String day;
WeekDay(String day) {
this.day= day;
}
public String getDay() {
return this.day;
}
}
现在使用注释我执行如下操作。
@MyAnnotation(WeekDay.SUNDAY.getDay())
public void getResult(String id){
}
上面的代码在eclipse中编译错误。它表示注释属性 MyAnnotation.value 的值必须是常量表达式。我在这里做错了什么吗?
谢谢!
最佳答案
更改自:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
致:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
WeekDay value();
}
并像这样使用它:
@MyAnnotation(WeekDay.SUNDAY)
如果您将字符串文字传递给当前注释,它也会起作用。将你的方法标记为final是行不通的,因为方法上的final只会阻止你重写它,而不会返回常量值。示例:
public final String getString() {
String[] strings = { "A", "B" };
return strings[new Random().nextInt(2)]; // returned value is not the same
}
关于java - 注释中的枚举中的引用值是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21375677/
我是一名优秀的程序员,十分优秀!