【发布时间】:2019-12-05 09:57:51
【问题描述】:
我正在尝试访问由许多枚举类实现的接口引用的枚举字段注释的参数。像这样的:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyAnnotation {
String someValue();
}
interface CommonInterface {}
enum FirstEnum implements CommonInterface{
@MyAnnotation(someValue = "abc")
A;
}
enum SecondEnum implements CommonInterface{
@MyAnnotation(someValue = "cde")
B;
}
void foo(CommonInterface enumValue){
String someValue; // get the parameter value
}
我通过向公共接口添加返回枚举类的反射信息的方法找到了一种解决方法,如下所示:
interface CommonInterface{
Class<? extends CommonInterface> getEnumClass();
String getName();
}
enum FirstEnum implements CommonInteface{
@MyAnnotation(someValue = "abc")
A;
public Class<? extends CommonInteface> getEnumClass() {
return getClass();
}
public String getName() {
return name();
}
}
void foo(CommonInterface enumValue){
MyAnnotation myAnnotation = enumValue.getEnumClass().getField(enumValue.getName()).getAnnotation(MyAnnotation.class);
}
有没有更好的方法来做同样的事情?我看到了一些解决方案,他们推荐了一个包装枚举类,该类将接口引用的枚举值作为构造函数参数。在我的情况下这不是很可行,因为这些枚举中会有很多实现公共接口并且每个都有很多值,所以维护它不会很好。
谢谢
【问题讨论】:
标签: java enums interface annotations