Introspector內省機制學習

一、內省機制是用來操做javabean。 java

二、java屬性是指 get或者set方法,跟變量無關。 spa

三、內省的基本操做 code

內省一個類,獲取出Bean的方法。 對象


BeanInfo bean = Introspector.getBeanInfo(Person.class);
獲取全部的屬性描述器



PropertyDescriptor[] descriptors = bean.getPropertyDescriptors();//獲取全部屬性的屬性描述器
獲取屬性的名字



descriptor.getName();


整段代碼 繼承


public void test7() throws IntrospectionException {
        BeanInfo bean = Introspector.getBeanInfo(Person.class);
        PropertyDescriptor[] descriptors = bean.getPropertyDescriptors();//獲取全部屬性的屬性描述器
        for (PropertyDescriptor  descriptor:descriptors){
              print(descriptor.getName());
        }
    }

生成的結果會包含Person裏的全部屬性和一個class屬性,而class屬性是Object裏的,因此當咱們須要一個完整Person而不包含繼承來的屬性的時候須要排除掉。 ip

BeanInfo bean = Introspector.getBeanInfo(Person.class,Object.class);


四、利用內省機制來使用屬性 get

實例化bean對象而且使用屬性描述器來獲取bean中的屬性,以name爲例子,name必須有符合javabean規範get set方法 it

Person p  = new Person();
PropertyDescriptor descriptor = new PropertyDescriptor("name",Person.class);
獲取set方法而且設值

Method writeMethod = descriptor.getWriteMethod();
writeMethod.invoke(p,"中國");
獲取get方法獲取值

Method readMethod = descriptor.getReadMethod();
Object invoke = readMethod.invoke(p, null);
print((String) invoke);
獲取某個變量的類型

Class<?> propertyType = descriptor.getPropertyType();
print(propertyType.toString());
相關文章
相關標籤/搜索