集册 Java实例教程 通过反射设置私有字段值

通过反射设置私有字段值

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

412
通过反射设置私有字段值

import java.lang.reflect.Field;
/** 来 自 N o  w  J a v a . c o m - 时  代  Java**/

public class FieldTroubleToo {

    public final boolean b = true;


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

        FieldTroubleToo ft = new FieldTroubleToo();

        try {

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

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

            //       f.setAccessible(true);  // solution

            f.setBoolean(ft, Boolean.FALSE); // IllegalAccessException


            // production code should handle these exceptions more gracefully

        } catch (NoSuchFieldException x) {

            x.printStackTrace();

        } catch (IllegalArgumentException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        }

    }
    /*
    来 自*
     nowjava
    */

}


展开阅读全文