通过反射实现对某个对象属性的注入

直接上代码  

辅助类   Student :

public class Student {

	private String name;
	private int age;

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
}

测试类  :

public class WireProperToObjectByReflect {
	//参数obj:要 注入的对象  properName:属性名   value:属性值
	public static Object wire(Object obj,String properName,Object value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		//获取该类的类型
		Class<? extends Object> clazz = obj.getClass();
		//获取对象的属性
		Field  field_name = clazz.getDeclaredField(properName);
		//开启访问权限
		field_name.setAccessible(true);
		//为该属性注入值
		field_name.set(obj, value);
		//返回该对象
		return obj;
		
	}
	public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		Student student=new Student();
		Student stu = (Student)wire(student, "name", "张三");
		System.out.println(stu);
	}

}

得到的结果:

Student [name=张三, age=0]
发布了41 篇原创文章 · 获赞 1 · 访问量 1866

猜你喜欢

转载自blog.csdn.net/qq_38087131/article/details/105289556