Reputation: 2073
I need to write a service level api that exposes any enumeration at run-time. The name of the enum will be passed as a string parameter to the service layer. So that means I need to use reflection.
All of the answers I've found so far deal with knowing ahead of time the name of the enumeration.
Upvotes: 0
Views: 70
Reputation: 559
You can use this :
public static <E extends Enum<E>> List<E> getValues(final String className) throws ClassNotFoundException {
List<E> lst = null;
if(className != null) {
Class<E> clazz = Class.forName(className);
E[] enumConstants = (E[]) clazz.getEnumConstants();
lst = Arrays.asList(enumConstants);
}
return lst;
}
Upvotes: 1
Reputation: 170158
Try something like this:
package demo;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
// ClassNotFoundException thrown when demo.Color does not exist
Class<?> enumType = Class.forName("demo.Color");
// constants is null when demo.Color is not an enum
Object[] constants = enumType.getEnumConstants();
System.out.println("is " + enumType + " an enum? " + enumType.isEnum());
System.out.println(Arrays.toString(constants));
}
}
enum Color {
GREEN,
BLUE
}
Upvotes: 1