Get values ​​from Enum, known only in Runtime

I need to get all the values ​​from an enumeration whose type will be known only at runtime. I came up with the following, but would like to know if anyone knows a better way:

enum TestEnum { FOO, BAR } Enum[] getValuesForEnum(Class type) { try { Method m = type.getMethod("values"); return (Enum[])m.invoke(null); } catch (Exception e) { throw new RuntimeException(e); } } Class testEnum = Class.forName("TestEnum"); getValuesForEnum(testEnum); 

Thanks!

+4
source share
4 answers

Instead, use the available API:

 T[] getValuesForEnum(Class<T> type) { return type.getEnumConstants(); } 

From Javadoc :

Returns the elements of this class enum or null if this class object does not represent an enumeration type.

Please note that I turned your method into a generic one to make it typafe. This way you don't need descending ones to get the actual enum values ​​from the returned array. (Of course, this makes the method so trivial that you can omit it and directly call type.getEnumConstants()

+16
source

Here's a variant of Kevin Stambridge's answer , which preserves the type (avoiding lowering), while preserving call protection with a non-enum type:

 static <E extends Enum<E>> E[] getValuesForEnum(Class<E> clazz) { return clazz.getEnumConstants(); } 
+8
source

I am using type.getEnumConstants ().

+5
source

I think this works:

 Enum<?>[] getValuesForEnum(Class<Enum<?>> enumType) { return enumType.getEnumConstants(); } 
+3
source

Source: https://habr.com/ru/post/1336801/


All Articles