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; }
|