集册 Java实例教程 枚举的构造函数使用反射进行获取和调用

枚举的构造函数使用反射进行获取和调用

欢马劈雪     最近更新时间:2020-01-02 10:19:05

562
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
枚举的构造函数使用反射进行获取和调用

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();

        }

    }

}


展开阅读全文