通过反射 修改访问和修改属性的值 Day25

package com.sxt.field;
/*
 * 通过反射拿到属性值
 *       修改public属性值 
 *       修改private属性值
 * 缺点:可读性差;代码复杂
 * 优点:灵活;可以访问修改private属性值
 * 以后多运用setXxx getXxx 修改属性的值
 */
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class TestField {
    public static void main(String[] args) throws Exception {
        //设置私有属性值
        Class<?> class1 = Class.forName("com.sxt.entity.Student");
        //创建对象
        Object obj = class1.newInstance();
        Field[] fields = class1.getDeclaredFields();
        //遍历所有属性
        for(Field f : fields){
            System.out.println(f.getName()+"	"+Modifier.toString(f.getModifiers()));
        }
        System.out.println("----------------------------------");
        
        //修改public的score的属性值
        Field field1 = class1.getDeclaredField("score");
        //直接通过方法(基本数据类型)
        field1.setDouble(obj, 99.9);
        double d = field1.getDouble(obj);
        System.out.println(d);
        
        System.out.println("----------------------------------");
        
        //拿到private的name的属性值
        Field field2 = class1.getDeclaredField("name");
        System.out.println(field2.getName() +" "+ Modifier.toString(field2.getModifiers()));
        //可以改变私有属性值
        field2.setAccessible(true);
        field2.set(obj, "小明");
        Object object = field2.get(obj);
        System.out.println(object);
    }
}
原文地址:https://www.cnblogs.com/qingfengzhuimeng/p/6809744.html