集册 Java实例教程 使用反射获取枚举常量

使用反射获取枚举常量

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

460
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用反射获取枚举常量

import java.util.Arrays;/*NowJava.com 提 供*/

import static java.lang.System.out;


enum Eon {

    HADEAN, ARCHAEAN, PROTEROZOIC, PHANEROZOIC

}


public class EnumConstants {

    public static void main(String... args) {

        try {

            Class<?> c = (args.length == 0 ? Eon.class : Class

                    .forName(args[0]));

            out.format("Enum name:  %s%nEnum constants:  %s%n",

                    c.getName(), Arrays.asList(c.getEnumConstants()));

            if (c == Eon.class)

                out.format("  Eon.values():  %s%n",

                        Arrays.asList(Eon.values()));


            // production code should handle this exception more gracefully

        } catch (ClassNotFoundException x) {
        /*
        时代Java 提供
        */

            x.printStackTrace();

        }

    }

}


展开阅读全文