Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get annotations for enum type variable

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?

like image 895
Timofey Gorshkov Avatar asked Aug 31 '11 08:08

Timofey Gorshkov


People also ask

Can you use == for enum?

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.

What variable type is enum?

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.

Can Enums have attributes?

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).

Can Enums have variables?

Methods and variables in an enumeration Enumerations are similar to classes and, you can have variables, methods, and constructors within them.


2 Answers

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 :)

like image 138
Tobias Avatar answered Sep 22 '22 23:09

Tobias


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.

like image 21
Timofey Gorshkov Avatar answered Sep 22 '22 23:09

Timofey Gorshkov