Created
June 9, 2012 12:13
-
-
Save lysu/2900771 to your computer and use it in GitHub Desktop.
Java:Create enum at runtime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Constructor con = Test.class.getDeclaredConstructors()[0]; | |
Method[] methods = con.getClass().getDeclaredMethods(); | |
for (Method m : methods) { | |
if (m.getName().equals("acquireConstructorAccessor")) { | |
m.setAccessible(true); | |
m.invoke(con, new Object[0]); | |
} | |
} | |
Field[] fields = con.getClass().getDeclaredFields(); | |
Object ca = null; | |
for (Field f : fields) { | |
if (f.getName().equals("constructorAccessor")) { | |
f.setAccessible(true); | |
ca = f.get(con); | |
} | |
} | |
Method m = ca.getClass().getMethod( "newInstance", new Class[] { Object[].class }); | |
m.setAccessible(true); | |
Test v = (Test) m.invoke(ca, new Object[] { new Object[] { "ADD_NEW", Integer.MAX_VALUE } }); | |
System.out.println(v.getClass() + ":" + v.name() + ":" + v.ordinal()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment