BeanMap beanMap = new BeanMap(mockObject); System.out.println(beanMap); } }
调试截图:
存在和 cglib 一样的问题,虽然类型没问题但是属性名还是不对。
原因分析:
/** * Constructs a new <code>BeanMap</code> that operates on the * specified bean. If the given bean is <code>null</code>, then * this map will be empty. * * @param bean the bean for this map to operate on */ publicBeanMap(final Object bean){ this.bean = bean; initialise(); }
对于无参的以 get 开头的方法名从 index =3 处截取,如 getALong 截取后为 ALong, 如 getADouble 截取后为 ADouble。
然后去构造 PropertyDescriptor:
/** * Creates <code>PropertyDescriptor</code> for the specified bean * with the specified name and methods to read/write the property value. * * @param bean the type of the target bean * @param base the base name of the property (the rest of the method name) * @param read the method used for reading the property value * @param write the method used for writing the property value * @exception IntrospectionException if an exception occurs during introspection * * @since 1.7 */ PropertyDescriptor(Class<?> bean, String base, Method read, Method write) throws IntrospectionException { if (bean == null) { thrownew IntrospectionException("Target Bean class is null"); } setClass0(bean); setName(Introspector.decapitalize(base)); setReadMethod(read); setWriteMethod(write); this.baseName = base; }
底层使用 java.beans.Introspector#decapitalize 进行解析:
/** * Utility method to take a string and convert it to normal Java variable * name capitalization. This normally means converting the first * character from upper case to lower case, but in the (unusual) special * case when there is more than one character and both the first and * second characters are upper case, we leave it alone. * <p> * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays * as "URL". * * @param name The string to be decapitalized. * @return The decapitalized version of the string. */ publicstatic 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]); returnnew String(chars); }
从代码中我们可以看出 (1) 当 name 的长度 > 1,且第一个字符和第二个字符都大写时,直接返回参数作为PropertyDescriptor name。(2) 否则将 name 转为首字母小写
// 枚举数组,返回枚举名数组 if (pojo.getClass().isArray() && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) { int len = Array.getLength(pojo); String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = ((Enum<?>) Array.get(pojo, i)).name(); } return values; }
// 基本类型返回 pojo 自身 if (ReflectUtils.isPrimitives(pojo.getClass())) { return pojo; }
// Class 返回 name if (pojo instanceof Class) { return ((Class) pojo).getName(); }
Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo);
// 数组类型,递归 if (pojo.getClass().isArray()) { int len = Array.getLength(pojo); Object[] dest = new Object[len]; history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); dest[i] = generalize(obj, history); } return dest; } // 集合类型递归 if (pojo instanceof Collection<?>) { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = (pojo instanceof List<?>) ? new ArrayList<Object>(len) : new HashSet<Object>(len); history.put(pojo, dest); for (Object obj : src) { dest.add(generalize(obj, history)); } return dest; } // Map 类型,直接 对 key 和 value 处理 if (pojo instanceof Map<?, ?>) { Map<Object, Object> src = (Map<Object, Object>) pojo; Map<Object, Object> dest = createMap(src); history.put(pojo, dest); for (Map.Entry<Object, Object> obj : src.entrySet()) { dest.put(generalize(obj.getKey(), history), generalize(obj.getValue(), history)); } return dest; } Map<String, Object> map = new HashMap<String, Object>(); history.put(pojo, map);
// 开启生成 class 则写入 pojo 的class if (GENERIC_WITH_CLZ) { map.put("class", pojo.getClass().getName()); }
// 处理 get 方法 for (Method method : pojo.getClass().getMethods()) { if (ReflectUtils.isBeanPropertyReadMethod(method)) { ReflectUtils.makeAccessible(method); try { map.put(ReflectUtils.getPropertyNameFromBeanReadMethod(method), generalize(method.invoke(pojo), history)); } catch (Exception e) { thrownew RuntimeException(e.getMessage(), e); } } } // 处理公有属性 for (Field field : pojo.getClass().getFields()) { if (ReflectUtils.isPublicInstanceField(field)) { try { Object fieldValue = field.get(pojo); // 对象已经解析过,直接从缓存里读提高性能 if (history.containsKey(pojo)) { Object pojoGeneralizedValue = history.get(pojo); // 已经解析过该属性则跳过(如公有属性,且有 get 方法的情况) if (pojoGeneralizedValue instanceof Map && ((Map) pojoGeneralizedValue).containsKey(field.getName())) { continue; } } if (fieldValue != null) { map.put(field.getName(), generalize(fieldValue, history)); } } catch (Exception e) { thrownew RuntimeException(e.getMessage(), e); } } } return map; }
关键截图
org.apache.dubbo.common.utils.ReflectUtils#getPropertyNameFromBeanReadMethod public static String getPropertyNameFromBeanReadMethod(Method method) { if (isBeanPropertyReadMethod(method)) { // get 方法,则从 index =3 的字符小写 + 后面的字符串 if (method.getName().startsWith("get")) { return method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); } // is 开头方法, index =2 的字符小写 + 后面的字符串 if (method.getName().startsWith("is")) { return method.getName().substring(2, 3).toLowerCase() + method.getName().substring(3); } } return null; }