本帖最后由 谢威 于 2013-7-3 16:57 编辑
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class SetProperty{
public static void setProperty(Object obj, String propertyName, Object value) throws Exception{
PropertyDescriptor pd = new PropertyDescriptor(propertyName,Object.class);
Method methodSetX = pd.getWriteMethod();
methodSetX.invoke(obj, value);
}
public static void main(String[] args)throws Exception {
ReflectPoint rf = new ReflectPoint(3,5);//ReflectPoint类见下边
setProperty(rf,"x",7);
System.out.println(rf.getX());
}
}
public class ReflectPoint {
private int x;
public int y;
public ReflectPoint(int x, int y) {//构造方法
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
运行之后提示:
Exception in thread "main" java.beans.IntrospectionException: Method not found: isX
at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:89)
at java.beans.PropertyDescriptor.<init>(PropertyDescriptor.java:53)
at practice.five.SetProperty.setProperty(SetProperty.java:10)
at practice.five.SetProperty.main(SetProperty.java:20)
求高手告诉我哪错了,谢谢! |