| 代码如下: package com.itheima;
 import java.beans.*;
 import java.lang.reflect.*;
 public class Test5 {
 
 /**
 * 5、 存在一个JavaBean,它包含以下几种可能的属性:
 1:boolean/Boolean
 2:int/Integer
 3:String
 4:double/Double
 属性名未知,现在要给这些属性设置默认值,以下是要求的默认值:
 String类型的默认值为字符串 www.itheima.com
 int/Integer类型的默认值为100
 boolean/Boolean类型的默认值为true
 double/Double的默认值为0.01D.
 只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现
 * @param args
 */
 public static void main(String[] args) throws Exception
 {
 
 Class clazz = Class.forName("cn.heima.test.testBean");
 Object bean = clazz.newInstance();
 BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
 
 // System.out.println(beanInfo);
 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
 
 for (PropertyDescriptor pd : propertyDescriptors)
 {    // System.out.println(pd);    // 获取属性名
 Object name = pd.getName();    // 获取属性类型
 Object type = pd.getPropertyType();    // 获取get方法
 Method getMethod = pd.getReadMethod();    // 获取set方法
 Method setMethod = pd.getWriteMethod();
 if (!"class".equals(name))
 {
 if (setMethod != null)
 {
 if (type == boolean.class || type == Boolean.class)
 setMethod.invoke(bean, true);
 if (type == String.class)
 setMethod.invoke(bean, "www.itheima.com");
 if (type == int.class || type == Integer.class)
 setMethod.invoke(bean, 100);
 if (type == double.class || type == Double.class)
 setMethod.invoke(bean, 0.01D);
 }
 if (getMethod != null)
 System.out.println(type + " " + name + "=" + getMethod.invoke(bean, null));
 
 }
 }
 }
 }
 class testBean
 {
 private boolean b;  private Integer i;
 private String str;  private Double d;
 
 public Boolean getB() {return b;}
 
 public void setB(Boolean b)  {this.b = b; }
 
 public Integer getI() {   return i;  }
 
 public void setI(Integer 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;  }
 
 }
 
 |