JDK中提供了对JavaBean进行操作的一些API,这套API就称为内省。用内省这套api操作JavaBean比用普通类的方式更方便。
对JavaBean的简单内省操作
通过内省的方式对ReflectPoint对象中的成员变量进行读写操作。
public class ReflectPoint {
private int x ;
private 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;
}
public int getY() {
return y ;
}
public void setY(int y) {
this.y = y;
}
}import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 5);
String propertyName = "x";
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName, pt1.getClass());
Method readMethod = pd1.getReadMethod();
Object retVal = readMethod.invoke(pt1);
System. out.println(retVal); // 3
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, pt1.getClass());
Method writeMethod = pd2.getWriteMethod();
Object value = 7;
writeMethod.invoke(pt1,value);
System. out.println(pt1.getX()); // 7
}
}
|
|