首页 > 其他 > 详细

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

时间:2020-06-01 11:04:20      阅读:51      评论:0      收藏:0      [点我收藏+]

通过反射来修改,反射还能实现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);
    }
}

 

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

原文:https://www.cnblogs.com/shilipojianshen/p/13023813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!