java内省Introspector

大纲:

  1. JavaBean 规范
  2. 内省

一、JavaBean 规范

JavaBean —般需遵循以下规范。

  1. 实现 java.io.Serializable 接口。
  2.  javaBean属性是具有getter/setter方法的private成员变量。也可以只提供getter方法,这样的属性叫只读属性;也可以只提供setter方法,这样的属性叫只写属性。
  3. JavaBean 必须有一个空的构造函数
  4. JavaBean 必须有一个public构造函数

二、内省

  • 首先内省的本质也是利用反射
  • 通过内省可以快速拿到javaBean变量的getter与setter,从而快速操作bean对象。

测试用javaBean

public class Person {
    private String name ;
    private int age ;
    public void say(){
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

1.可以通过BeanInfo对象拿到JavaBean类中所有属性和方法的描述器

    public static void main(String[] args) throws Exception {
        //获取BeanInfo对象,主要用于获取javaBean的属性描述器
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
        //方法描述器
        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
        //属性描述器
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        //测试对象
        Person person = new Person();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            //属性名
            System.out.println("Person的属性:"+propertyDescriptor.getName());
            if("name".equals(propertyDescriptor.getName())){
                //属性读方法
                Method readMethod = propertyDescriptor.getReadMethod();
                //属性的写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(person,"xiaoming");
                System.out.println("person的name:"+readMethod.invoke(person));
                Class<?> propertyType = propertyDescriptor.getPropertyType();
                System.out.println("属性的类型:"+propertyType.getName());
            }
        }
    }

2.直接获取某个属性的描述器

    public static void main(String[] args) throws Exception {
        Person p = new Person();
        //直接通过名称获取属性描述器
        //获取name属性的描述器,方便我们直接操作p对象的name属性。
        PropertyDescriptor descriptor = new PropertyDescriptor("name", Person.class);
        Method writeMethod = descriptor.getWriteMethod();
        writeMethod.invoke(p,"nananan");
        System.out.println("person对象name:"+descriptor.getReadMethod().invoke(p));
    }

猜你喜欢

转载自www.cnblogs.com/liuboyuan/p/11120481.html