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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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:
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).
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: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.
Try this (java reflection):
It should get you the annotations from
AAA
.EDIT:
As the author supposed:
Works for him :)