Jdk版本:1.8.0_131 作者出于学习阶段,如有问题请指正
来自API的解释:PropertyDescriptor 描述 Java Bean 通过一对存储器方法导出的一个属性。
PropertyDescriptor有一个常用的功能:包装一个属性的Get、Set方法,通过反射调取相应的方法,举例:
构造一个PropertyDescriptor -> 获取get/set方法 -> invoke
在整个PropertyDescriptor中,有两个重要的概念:readMethod和writeMethod, 理解起来,可以当做是目前流行的Get方法和Set方法目前有如下构造器:
构造器中,若传入了Class,则会验证class,否则会忽略class PropertyDescriptor(String propertyName, Class<?> beanClass) 默认传入的readMethod和writeMethod为:is+属性名/set+属性名 PropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName) 默认构造器 PropertyDescriptor(String propertyName, Method readMethod, Method writeMethod) 忽略了class的包装propertyName的构造器,目前用的比较多的也是这个 PropertyDescriptor(Class<?> bean, String base, Method read, Method write) base和propertyName的区别是,当前构造器会调用Introspector.decapitalize(base)方法来设置属性名Introspector.decapitalize方法:
public static String decapitalize(String name) { if (name == null || name.length() == 0) { return name; } if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))){ return name; } char chars[] = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); }看不懂的话看下示例: name -> name Name ->name nAme -> nAme NAME -> NAME
getPropertyType/setPropertyType方法:
getPropertyType返回属性的Java类型信息。注意Class对象可能会描述原始Java类型,例如int。 这种类型是由read方法返回的,或者用作write方法的参数类型。 如果类型是不支持非索引访问的索引属性,则返回null。
public synchronized Class<?> getPropertyType() { Class<?> type = getPropertyType0(); if (type == null) { try { type = findPropertyType(getReadMethod(), getWriteMethod()); setPropertyType(type); } catch (IntrospectionException ex) { // Fall } } return type; }findPropertyType方法如下:
private Class<?> findPropertyType(Method readMethod, Method writeMethod) throws IntrospectionException { Class<?> propertyType = null; try { if (readMethod != null) { Class<?>[] params = getParameterTypes(getClass0(), readMethod); if (params.length != 0) { throw new IntrospectionException("bad read method arg count: " + readMethod); } propertyType = getReturnType(getClass0(), readMethod); if (propertyType == Void.TYPE) { throw new IntrospectionException("read method " + readMethod.getName() + " returns void"); } } if (writeMethod != null) { Class<?>[] params = getParameterTypes(getClass0(), writeMethod); if (params.length != 1) { throw new IntrospectionException("bad write method arg count: " + writeMethod); } if (propertyType != null && !params[0].isAssignableFrom(propertyType)) { throw new IntrospectionException("type mismatch between read and write methods"); } propertyType = params[0]; } } catch (IntrospectionException ex) { throw ex; } return propertyType; }该类的使用案例:http://blog.csdn.net/z6913787/arti/8443777 关键的代码没问题,其余的方法没有太多可以说的地方,如有不懂的地方请及时留言