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?
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).
Methods and variables in an enumeration Enumerations are similar to classes and, you can have variables, methods, and constructors within them.
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With