/*1、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
public void setProperty(Object obj, String propertyName, Object value){
}
*/
package com.itheima;
import java.lang.reflect.*;
class Person1{
private String name;
private int 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;
}
public Person1(String name, int age) {
//super();
this.name = name;
this.age = age;
}
public String toString() {
return "Person1 [name=" + name + ", age=" + age + "]";
}
}
public class Test1 {
public static void main(String args[])throws Exception{
//创建一个对象
Person1 p=new Person1("zhangsan",23);
System.out.println(p.toString());
//调用setProperty方法
setProperty(p,"age",18);
System.out.println(p.toString());
}
/*此方法可将obj对象中名为propertyName的属性的值设置为value.
* */
public static void setProperty(Object obj, String propertyName, Object value)throws Exception{
//Field[] declaredFields = obj.getClass().getDeclaredFields(propertyName);
//通过反射获得相应字段
Field field=obj.getClass().getDeclaredField(propertyName);
//设置暴力反射
field.setAccessible(true);
//设置字段值
field.set(obj, value);
}
}
|
|