访问已实现接口引用的枚举的注释



我正在尝试访问由许多枚举类实现的接口引用的枚举字段注释的参数。像这样:

@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);
}

有没有更好的方法来做同样的事情?我看到一些解决方案,他们推荐一个包装器枚举类,该类将接口引用的枚举值作为构造函数参数。就我而言,这不是很可行,因为会有很多这样的枚举实现通用接口,每个枚举都有很多值,所以维护它并不好。

谢谢

您无需通过CommonInterface公开getEnumClass(),在实例上调用getClass()就足够了。同样,为什么要调用你的方法getName()为什么不直接调用它name()这样它就可以由 Enum 隐式实现?

你可以做这样的事情,而无需向 CommonInterface 添加任何方法:

void foo(CommonInterface enumValue) throws Exception {
String name = enumValue.getClass().getMethod("name").invoke(enumValue).toString();
MyAnnotation myAnnotation = enumValue.getClass().getField(name).getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.someValue());
}

这很危险,因为它假设 CommonInterface 的所有实现都是枚举,因此具有name()方法。为了使你认为"更安全",如果你有一个不是枚举的CommonInterface实现,请将"name"方法添加到CommonInterface:

interface CommonInterface {
String name();
}

然后你的"foo"方法变成:

void foo(CommonInterface enumValue) throws Exception {
MyAnnotation myAnnotation = enumValue.getClass().getField(enumValue.name()).getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.someValue());
}

最新更新