提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
枚举的构造函数使用反射进行获取和调用
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /* from n o w j a v a . c o m*/ import static java.lang.System.out; enum Charge { POSITIVE, NEGATIVE, NEUTRAL; Charge() { out.format("under construction%n"); } } public class EnumTrouble { public static void main(String... args) {/**时 代 J a v a 公 众 号**/ try { Class<?> c = Charge.class; Constructor[] ctors = c.getDeclaredConstructors(); for (Constructor ctor : ctors) { out.format("Constructor: %s%n", ctor.toGenericString()); ctor.setAccessible(true); ctor.newInstance(); } // production code should handle these exceptions more gracefully } catch (InstantiationException x) { x.printStackTrace(); } catch (IllegalAccessException x) { x.printStackTrace(); } catch (InvocationTargetException x) { x.printStackTrace(); } } }