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

通过反射设置字段值

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

550
通过反射设置字段值
/*来 自 时 代 J a v a*/

import java.lang.reflect.Field;


public class FieldTrouble {

    public Integer val;


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

        FieldTrouble ft = new FieldTrouble();

        try {

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

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

            f.setInt(ft, 42); // IllegalArgumentException


            // production code should handle these exceptions more gracefully

        } catch (NoSuchFieldException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        }

    }

}
/* from 
n o w j a v a . c o m - 时代Java*/


展开阅读全文