java反射修改字段值

package com.heima.reflect;

public class Demo008 {

	public static void main(String[] args) throws Exception {
		Student s = new Student("张三", 23);
		System.out.println(s);
		
		Tool.setProperty(s, "name", "李四");
		
		System.out.println(s);
		
	}

}

class Student {
	private String name;
	private int age;
	public Student() {
		super();
		
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}
public class Tool {
	
	public  static void setProperty(Object obj, String propertyName, Object value) throws Exception{
		Class<? extends Object> clazz = obj.getClass();
		
		//防止字段为private时,无法修改字段值的情况
		Field field = clazz.getDeclaredField(propertyName);//暴力反射获取字段
		field.setAccessible(true);//去除权限
		
		field.set(obj, value);
	}
	
}

 

    原文作者:91奔跑的蜗牛
    原文地址: https://blog.csdn.net/xldmx/article/details/89219035
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞