获取枚举类型变量的注释
我有一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个(java反射):
它应该让你从
AAA
获得注释。编辑:
正如作者所认为的:
为他工作:)
Try this (java reflection):
It should get you the annotations from
AAA
.EDIT:
As the author supposed:
Works for him :)
正如我已经提供的:
更清楚地说:
在这种情况下,我们不需要知道
en1
的真实类。另请参阅:有关混淆大小写的评论。
As I've already offered:
To be clearer:
In this case we have no need to know real class of
en1
.See also: remark about obfuscated case.
我刚刚从你的评论中读到你已经找到了答案。我只是想向其他感兴趣的人指出,为了使其发挥作用,必须使用正确的保留策略声明这些注释,如下所示:
如果没有此策略,它们将无法在运行时访问。
进一步阅读:
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:
Without this, they will not be accessible at runtime.
Further reading:
如果您使用混淆器(例如 Proguard),您可能会发现枚举字段已被重命名,而
.name()
仍然返回字段的原始名称。例如,这个枚举......在 ProGuarding 后会变成这样...
...但是
En.FOO.name()
仍会返回"FOO"
,导致getField(En.FOO.name())
失败,因为它期望该字段被命名为"a"
。如果您想从混淆代码中获取特定枚举字段的
Field
,您可以这样做: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......would become this after ProGuarding...
...but
En.FOO.name()
will still return"FOO"
, causinggetField(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:除了现有答案之外,如果您控制枚举类(可以编辑它),您可以简单地向枚举添加一个方法来获取所需的注释,即
或其所有注释:
调整上面的代码以处理异常(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.
or all it's annotations:
Adjust the code above to handle exceptions (NoSuchFieldException and SecurityException).