1、内省机制是用来操作javabean。
2、java属性是指 get或者set方法,跟变量无关。
3、内省的基本操作
内省一个类,获取出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而不包含继承来的属性的时候需要排除掉。
BeanInfo bean = Introspector.getBeanInfo(Person.class,Object.class);
4、利用内省机制来使用属性
实例化bean对象并且使用属性描述器来获取bean中的属性,以name为例子,name必须有符合javabean规范get set方法
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());