集册 Java实例教程 使用反射设置枚举常量值

使用反射设置枚举常量值

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

536
使用反射设置枚举常量值

import java.lang.reflect.Field;

import static java.lang.System.out;


enum TraceLevel {
/*
 from 时代Java公众号 - N o w J a  v a . c o m 
*/

    OFF, LOW, MEDIUM, HIGH, DEBUG

}


class MyServer {

    private TraceLevel level = TraceLevel.OFF;

}


public class SetTrace {

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

        TraceLevel newLevel = TraceLevel.valueOf(args[0]);
// from n o w j a v a . c o m

        try {

            MyServer svr = new MyServer();

            Class<?> c = svr.getClass();

            Field f = c.getDeclaredField("level");

            f.setAccessible(true);

            TraceLevel oldLevel = (TraceLevel) f.get(svr);

            out.format("Original trace level:  %s%n", oldLevel);


            if (oldLevel != newLevel) {

                f.set(svr, newLevel);

                out.format("    New  trace level:  %s%n", f.get(svr));

            }


            // production code should handle these exceptions more gracefully

        } catch (IllegalArgumentException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        } catch (NoSuchFieldException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文