本帖最后由 xscn 于 2013-8-24 10:30 编辑
用beaninfo批量操作javabean的时候的代码- package cn.itcast.day1;
- import java.beans.*;
- import java.lang.reflect.*;
- public class IntroSpectorDemo2 {
- public static void main(String args[])throws Exception {
- BeanDemo bd = new BeanDemo();
- introSpector(bd);
-
- }
- private static void introSpector(Object bd)throws Exception {
- BeanInfo bi = Introspector.getBeanInfo(bd.getClass());
- PropertyDescriptor[] pd = bi.getPropertyDescriptors();
-
- for (PropertyDescriptor pds : pd) {
- String propertName=pds.getName();
- Class propertClass=pds.getPropertyType();
- Method writeMethod=pds.getWriteMethod();
-
-
- //if(propertName.equals("name"))
- // writeMethod.invoke(bd, "zhangsan");
-
- //else if(propertName.equals("age"))
- // writeMethod.invoke(bd, 20);
- if(propertClass==String.class)
- writeMethod.invoke(bd,"zhangsan1");
- else if(propertClass==int.class)//
- writeMethod.invoke(bd,21);
-
- Method readMethod = pds.getReadMethod();
- Object retval = readMethod.invoke(bd);
- System.out.println(retval);
-
- }
- }
- }
复制代码 打印结果
21
class cn.itcast.day1.BeanDemo
zhangsan1
用PropertyDescriptor匹配属性名和属性类型都有这个class cn.itcast.day1.BeanDemo
问题就是第二行这个东西是怎么来的????????
下面附上Javabean类,帮忙找找原因- package cn.itcast.day1;
- public class BeanDemo {
- private String n;
- private int a;
- public BeanDemo() {
- super();
- }
- public String getName() {
- return n;
- }
- public void setName(String name) {
- this.n = name;
- }
- public int getAge() {
- return a;
- }
- public void setAge(int age) {
- this.a = age;
- }
- }
复制代码 |