public static void main(String[] args) throws Exception {
JavaBean javaBean = new JavaBean();
BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for( PropertyDescriptor propertyDescriptor : propertyDescriptors )
{
// 获取属性名
String name = propertyDescriptor.getName();
// 获取属性类型
Object type = propertyDescriptor.getPropertyType();
//获取get方法
Method readMethod = propertyDescriptor.getReadMethod();
// 获取set方法
Method writeMethod = propertyDescriptor.getWriteMethod();
if( !"class".equals(name))
{
if( writeMethod != null )
{
if(type == boolean.class || type == Boolean.class){
writeMethod.invoke(javaBean, true);
}
if(type == int.class || type == Integer.class){
writeMethod.invoke(javaBean, 100);
}
if(type == String.class){
writeMethod.invoke(javaBean, "www.itheima.com");
}
if(type == double.class || type == Double.class){
writeMethod.invoke(javaBean, 0.01D);
}
}
if( readMethod != null)
{
System.out.println(type + ":"+readMethod.invoke(javaBean, null));
}
}
}
}
}
class JavaBean{
private boolean b;
private int i;
private String str;
private double d;
public boolean isB() {
return b;
}
public void setB(boolean b) {
this.b = b;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
} |
|