Java Bean 转 Map 的巨坑,注意了!!!
往期热门文章:
一、背景
二、那些坑
2.0 测试对象
import lombok.Data;
import java.util.Date;
@Data
public class MockObject extends MockParent{
private Integer aInteger;
private Long aLong;
private Double aDouble;
private Date aDate;
}
import lombok.Data;
@Data
public class MockParent {
private Long parent;
}
2.1 JSON 反序列化了类型丢失
2.1.1 问题复现
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.8</version>
</dependency>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.util.Date;
import java.util.Map;
public class JsonDemo {
public static void main(String[] args) {
MockObject mockObject = new MockObject();
mockObject.setAInteger(1);
mockObject.setALong(2L);
mockObject.setADate(new Date());
mockObject.setADouble(3.4D);
mockObject.setParent(3L);
String json = JSON.toJSONString(mockObject);
Map<String,Object> map = JSON.parseObject(json, new TypeReference<Map<String,Object>>(){});
System.out.println(map);
}
}
{"parent":3,"ADouble":3.4,"ALong":2,"AInteger":1,"ADate":1657299916477}
2.2.2 问题描述
2.2 BeanMap 转换属性名错误
2.2.1 commons-beanutils 的 BeanMap
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
import org.apache.commons.beanutils.BeanMap;
import third.fastjson.MockObject;
import java.util.Date;
public class BeanUtilsDemo {
public static void main(String[] args) {
MockObject mockObject = new MockObject();
mockObject.setAInteger(1);
mockObject.setALong(2L);
mockObject.setADate(new Date());
mockObject.setADouble(3.4D);
mockObject.setParent(3L);
BeanMap beanMap = new BeanMap(mockObject);
System.out.println(beanMap);
}
}
/**
* 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
*/
public BeanMap(final Object bean) {
this.bean = bean;
initialise();
}
private void initialise() {
if(getBean() == null) {
return;
}
final Class<? extends Object> beanClass = getBean().getClass();
try {
//BeanInfo beanInfo = Introspector.getBeanInfo( bean, null );
final BeanInfo beanInfo = Introspector.getBeanInfo( beanClass );
final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if ( propertyDescriptors != null ) {
for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if ( propertyDescriptor != null ) {
final String name = propertyDescriptor.getName();
final Method readMethod = propertyDescriptor.getReadMethod();
final Method writeMethod = propertyDescriptor.getWriteMethod();
final Class<? extends Object> aType = propertyDescriptor.getPropertyType();
if ( readMethod != null ) {
readMethods.put( name, readMethod );
}
if ( writeMethod != null ) {
writeMethods.put( name, writeMethod );
}
types.put( name, aType );
}
}
}
}
catch ( final IntrospectionException e ) {
logWarn( e );
}
}
BeanInfo
里面 PropertyDescriptor
的 name 不正确。java.beans.Introspector#getTargetPropertyInfo
方法是字段解析的关键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) {
throw new 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.
*/
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);
}
PropertyDescriptor
name。(2) 否则将 name 转为首字母小写2.2.2 使用 cglib 的 BeanMap
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.12</version>
</dependency>
import net.sf.cglib.beans.BeanMap;
import third.fastjson.MockObject;
import java.util.Date;
public class BeanMapDemo {
public static void main(String[] args) {
MockObject mockObject = new MockObject();
mockObject.setAInteger(1);
mockObject.setALong(2L);
mockObject.setADate(new Date());
mockObject.setADouble(3.4D);
mockObject.setParent(3L);
BeanMap beanMapp = BeanMap.create(mockObject);
System.out.println(beanMapp);
}
}
net.sf.cglib.core.ReflectUtils#getBeanGetters
底层也会用到 java.beans.Introspector#decapitalize
所以属性名存在一样的问题就不足为奇了。三、解决办法
3.1 解决方案
<!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>3.0.9</version>
</dependency>
import org.apache.dubbo.common.utils.PojoUtils;
import third.fastjson.MockObject;
import java.util.Date;
public class DubboPojoDemo {
public static void main(String[] args) {
MockObject mockObject = new MockObject();
mockObject.setAInteger(1);
mockObject.setALong(2L);
mockObject.setADate(new Date());
mockObject.setADouble(3.4D);
mockObject.setParent(3L);
Object generalize = PojoUtils.generalize(mockObject);
System.out.println(generalize);
}
}
3.2 原理解析
org.apache.dubbo.common.utils.PojoUtils#generalize(java.lang.Object)
public static Object generalize(Object pojo) {
eturn generalize(pojo, new IdentityHashMap());
}
// pojo 待转换的对象
// history 缓存 Map,提高性能
private static Object generalize(Object pojo, Map<Object, Object> history) {
if (pojo == null) {
return null;
}
// 枚举直接返回枚举名
if (pojo instanceof Enum<?>) {
return ((Enum<?>) pojo).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) {
throw new 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) {
throw new 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;
}
四、总结
最近热文阅读:
1、为什么 "𠮷𠮷𠮷".length !== 3 ? 2、还在用XShell?Tabby安排上... 3、Spring Batch 批处理,骚气还强大! 4、我的mybatis-plus用法,被全公司同事开始悄悄模仿了! 5、Spring是如何管理事务的之@Transactional注解详解 6、面试官:如果要存 IP 地址,用什么数据类型比较好?99%人都会答错! 7、面试官:为什么不能将实数作为 HashMap 的 key? 8、Redis 官方可视化工具,高颜值,功能太强大! 9、不好意思, Maven 该换了! 10、面试官 | Spring Boot 项目如何统一结果,统一异常,统一日志? 关注公众号,你想要的Java都在这里
评论