如何修改对象私有字段的值

通过反射来修改,反射还能实现swap(int a,int b)

package zhengze;

import java.lang.reflect.Field;
import java.util.logging.FileHandler;

public class Person {
    private int id;
    private String name;
    private int sex;
    Person(int a,String b, int c)
    {
        id = a;
        name = b;
        sex = c;
    }
    public void setName(String name) {
        this.name = name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    public int getSex() {
        return sex;
    }

    @Override
    public String toString() {
        return super.toString()+" "+name;
    }

    public static void main(String[] args) throws Exception{
        Person person = new Person(1,"liy",1);
        Class c = person.getClass();
        System.out.println(c);
        Field f = c.getDeclaredField("name");
        System.out.println(f.getName());
        f.setAccessible(true);
        f.set(person,"liyming");
        System.out.println(person);
    }
}

 

posted @ 2020-06-01 10:32  十里坡剑神—》》》》  阅读(163)  评论(0编辑  收藏  举报