package com.itheima;
import java.lang.reflect.Field;
/*
* 3、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
public void setProperty(Object obj, String propertyName, Object value){
}
* */
public class Test3 {
public static void main(String[] args) {
M obj = new M();
Method method = new Method();
method.setProperty(obj, "propertyName", "你好");
}
}
class Method{
Class c = null;
Field f = null;
Object obj = null;
public void setProperty(Object obj , String propertyName, Object value){
this.obj = obj;
//获取obj对象的字节码
c = obj.getClass();
System.out.println(c);
try {
Field f = c.getDeclaredField(propertyName);
System.out.println(f);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
f.set( obj, value);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class M{
String propertyName = "shangzhipeng";
}
红色字体处出现java.lang.NullPointerException异常,怎么也调不对、、 |
|