获取枚举类型变量的注释

发布于 2024-12-02 18:05:38 字数 211 浏览 2 评论 0原文

我有一些 Enum 类型。问题是:如何获取en1变量引用的枚举常量相关的注解?

I have some nonnull variable (e.g. en1) of Enum type. The question is: how to get annotations related to enumeration constant referenced by en1 variable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

背叛残局 2024-12-09 18:05:38

试试这个(java反射):

String field = En.AAA.name();
En.class.getField(field).getAnnotations();

它应该让你从AAA获得注释。

编辑:

正如作者所认为的:

en1.getClass().getField(((Enum)en1).name()).getAnnotations(); 

为他工作:)

Try this (java reflection):

String field = En.AAA.name();
En.class.getField(field).getAnnotations();

It should get you the annotations from AAA.

EDIT:

As the author supposed:

en1.getClass().getField(((Enum)en1).name()).getAnnotations(); 

Works for him :)

花间憩 2024-12-09 18:05:38

正如我已经提供的:

en1.getClass().getField(((Enum)en1).name()).getAnnotations();

更清楚地说:

String name = e.name(); // Enum method to get name of presented enum constant
Annotation[] annos = e.getClass().getField(name).getAnnotations(); // Classical reflection technique

在这种情况下,我们不需要知道 en1 的真实类。

另请参阅:有关混淆大小写的评论

As I've already offered:

en1.getClass().getField(((Enum)en1).name()).getAnnotations();

To be clearer:

String name = e.name(); // Enum method to get name of presented enum constant
Annotation[] annos = e.getClass().getField(name).getAnnotations(); // Classical reflection technique

In this case we have no need to know real class of en1.

See also: remark about obfuscated case.

遗心遗梦遗幸福 2024-12-09 18:05:38

我刚刚从你的评论中读到你已经找到了答案。我只是想向其他感兴趣的人指出,为了使其发挥作用,必须使用正确的保留策略声明这些注释,如下所示:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Anno1 {
   // ...
}

如果没有此策略,它们将无法在运行时访问。

进一步阅读:

I just read from your comment that you already found the answer. I just wanted to remark for other people interested that, in order for that to work, those annotations must have been declared with the correct retention policy, like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Anno1 {
   // ...
}

Without this, they will not be accessible at runtime.

Further reading:

盗琴音 2024-12-09 18:05:38

如果您使用混淆器(例如 Proguard),您可能会发现枚举字段已被重命名,而 .name() 仍然返回字段的原始名称。例如,这个枚举...

enum En {
    FOO,
    BAR
}

...在 ProGuarding 后会变成这样...

enum En {
    a,
    b
}

...但是 En.FOO.name() 仍会返回 "FOO" ,导致 getField(En.FOO.name()) 失败,因为它期望该字段被命名为 "a"

如果您想从混淆代码中获取特定枚举字段的 Field,您可以这样做:

for (Field field : En.class.getDeclaredFields()) {
    if (field.isEnumConstant()) {
        try {
            if (en1 == field.get(null)) {
                Annotation[] annotations = field.getAnnotations();
            }
        } catch (IllegalAccessException e) {
            // 
        }
    }
}

If you are using an obfuscator such as Proguard, you might find that the enum fields have been renamed, while .name() still returns the original name of the field. For example, this enum...

enum En {
    FOO,
    BAR
}

...would become this after ProGuarding...

enum En {
    a,
    b
}

...but En.FOO.name() will still return "FOO", causing getField(En.FOO.name()) to fail because it expects the field to be named "a".

If you want to get the Field for a specific enum field from obfuscated code, you can do this:

for (Field field : En.class.getDeclaredFields()) {
    if (field.isEnumConstant()) {
        try {
            if (en1 == field.get(null)) {
                Annotation[] annotations = field.getAnnotations();
            }
        } catch (IllegalAccessException e) {
            // 
        }
    }
}
美羊羊 2024-12-09 18:05:38

除了现有答案之外,如果您控制枚举类(可以编辑它),您可以简单地向枚举添加一个方法来获取所需的注释,即

AnnotationClass getAnnotation(){
   Field field = this.getClass().getField(this.name());
   return field.getAnnotation(AnnotationClass.class);       
}

或其所有注释:

Annotation[] getAnnotations(){
   Field field = this.getClass().getField(this.name());
   return field.getAnnotations();
}

调整上面的代码以处理异常(NoSuchFieldException和安全异常)。

Further to the existing answers, if you are in control of the enum class (can edit it), you could simply add a method to the enum to fetch the required annotation i.e.

AnnotationClass getAnnotation(){
   Field field = this.getClass().getField(this.name());
   return field.getAnnotation(AnnotationClass.class);       
}

or all it's annotations:

Annotation[] getAnnotations(){
   Field field = this.getClass().getField(this.name());
   return field.getAnnotations();
}

Adjust the code above to handle exceptions (NoSuchFieldException and SecurityException).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文