gpt4 book ai didi

java - 注释中的枚举中的引用值是什么?

转载 作者:行者123 更新时间:2023-12-01 13:34:39 25 4
gpt4 key购买 nike

我已经编写了自定义注释,并且如果我按如下方式使用它,则工作正常。

@MyAnnotation("sun")
public void getResult(String id){


}

MyAnnotation.java

@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com