Introspector类
内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。
JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。
PropertyDescriptor类:
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。
主要方法:
1. getPropertyType(),获得属性的Class对象;
2. getReadMethod(),获得用于读取属性值的方法;
getWriteMethod(),获得用于写入属性值的方法;
3. hashCode(),获取对象的哈希值;
4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
public class test { /** * @param pt1 类实体 * @param propertyName 属性名称 * @return * @throws Exception */ private static Object getProperty_2(Object pt1, String propertyName) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); Object reValue = null; for(PropertyDescriptor pd : pds){ if(pd.getName().equals(propertyName)){ Method methodGetX = pd.getReadMethod(); reValue = methodGetX.invoke(pt1); break; } } return reValue; } public static void main(String[] args) { ZTreeModel zTreeModel = new ZTreeModel(); zTreeModel.setName("root"); try { System.out.println(getProperty_2(zTreeModel, "name")); } catch (Exception e) { e.printStackTrace(); } } }