类 |
描述 |
BeanInfo |
对JavaBean进行描述的接口 |
Introspector |
描述所有的JavaBean的成员类 |
PropertyDescriptor |
描述的是JavaBean的属性类 |
shape.java
package reflect; public class Shape {
private int x=4;
int y;
protected int z;
public int h;
public Shape() {
}
public Shape(int x, Integer y) {
super();
this.x = x;
this.y = y; }
public Shape(int x, int y, int z, int h) {
super();
this.x = x;
this.y = y;
this.z = z;
this.h = h;
}
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;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
@Override
public String toString() {
return "Shape [x=" + x + ", y=" + y + ", z=" + z + ", h=" + h
+ ", getX()=" + getX() + ", getY()=" + getY() + ", getZ()="
+ getZ() + ", getH()=" + getH() + ", getClass()=" + getClass()
+ ", hashCode()=" + hashCode() + ", toString()="
+ super.toString() + "]";
} }
Shape shape=new Shape();
BeanInfo beaninfo=Introspector.getBeanInfo(Shape.class);
PropertyDescriptor []pds=beaninfo.getPropertyDescriptors();
//返回5个,其中还有一个是Object中的 getClass()和setClass(), 它是根据 getXxx和setXxx找的
System.out.println(pds.length);
PropertyDescriptor pd = pds[1]; //数组下标 按照字典顺序 第一个是 class、h、x、y、z
System.out.println(pd.getName());
Method setMethod=pd.getWriteMethod();
System.out.println(setMethod.getName());
setMethod.invoke(shape, 33);
System.out.println(pds[1].getReadMethod().invoke(shape,null));
结果:
5
h
setH
33