Skip to content

Instantly share code, notes, and snippets.

@lysu
Created June 9, 2012 12:13
Show Gist options
  • Save lysu/2900771 to your computer and use it in GitHub Desktop.
Save lysu/2900771 to your computer and use it in GitHub Desktop.
Java:Create enum at runtime
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