Timofey Gorshkov Timofey Gorshkov - 3 months ago 16
Java Question

Get annotations for enum type variable

I have some non

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

Answer

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.