import java.lang.reflect.Field;
public class Test1 {
/**
public void setProperty(Object obj, String propertyName, Object value){
}
* @param args
*/
private static String kind="dog";
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 a = new Test1();
setProperty sp =new setProperty();
//调用setProperty类中的方法,并将所要改变的值传递过去
sp.setProperty(a, "kind", "dog");
System.out.print("动物种类:"+Test1.kind);
}
}
class setProperty{
public void setProperty(Object obj, String propertyName, Object value)
{
try {
//获得反射对象
Field field = obj.getClass().getDeclaredField(propertyName);
//设置可以访问变量
field.setAccessible(true);
//将kind由dog改变为cat
field.set(obj,"cat");
} catch (Exception e) {
//改变失败则输出修改失败"修改失败"
System.out.println("修改失败");
}
}
}
|
|