gorootde
gorootde

Reputation: 4073

Get all enum values via a Class<?> reference

I am analyzing some fields of a class via reflection. If the type of a field is an enum type, I want to retrieve all values for this enum.

private MappedType mapType( final Class<?> c ) {
    ... 
    else if (Enum.class.isAssignableFrom( field ))
         {

            //This code is not valid
            final Enum<?> e = (Enum<?>) c;
            Object[] possibleValues=e.values();
            ...
            return MappedType.ENUM;
         }

How to retrieve a list of all possible enum values? (String names of the values would be sufficient)

Upvotes: 2

Views: 3171

Answers (1)

vinayknl
vinayknl

Reputation: 1252

See http://docs.oracle.com/javase/tutorial/reflect/special/enumMembers.html

Given a fully qualified name of an Enum class, you can find constants in it by

Class.getEnumConstants()

Assuming you are passing the Class of the field in field Variable, you can try as below

 else if (Enum.class.isAssignableFrom( field ))
 {
        Object[] possibleValues=field.getEnumConstants();
  //...
 }

Upvotes: 3

Related Questions