I found another option that should neither rename all enumeration constants nor throw an exception ... but it is implementation-specific, i.e. uses undocumented methods. It works for Sun JDK 1.6.0_20 (and was made by reading the source code from 1.6.0_13).
public static <E extends Enum<E>> boolean enumTypeContains(Class<E> e, String s) { try { Method enumDir = Class.class.getDeclaredMethod("enumConstantDirectory"); enumDir.setAccessible(true); Map<?,?> dir = (Map<?,?>)enumDir.invoke(e); return dir.containsKey(s); } catch(NoSuchMethodException ex) { throw new Error(ex); } catch(IllegalAccessException ex) { throw new Error(ex); } catch(InvocationTargetException ex) { throw new Error(ex.getCause()); } }
If we were in the java.lang , it might look something like this:
public static <E extends Enum<E>> boolean enumTypeContains(Class<E> e, String s) { return e.enumConstantDirectory().containsKey(s); }
Here we use the Class.enumConstantDirectory() method, which (on the first call) creates and (later only) returns a map with all enumeration constants as values, their names as the key. (It is precisely such a map that can be created manually).
This method is used inside Enum.valueOf(Class, String) and supposedly also EnumType.valueOf(String) (depends on the compiler).
The first time enumConstantDirectory or getEnumConstants() is called, the private helper method calls EnumType.values() (which is implemented by the compiler). The result is then reused for the following calls to these two methods.
Paŭlo Ebermann
source share