BeanUtils.copyProperties遇到Map异常

1,035 阅读1分钟

问题

对不同的类使用copyProperties,两个类的属性都一致

类A:

public class A {

    private Map<String, C> map;
    
    public static class C {

        private int a;

        private int b;

    }
    // 省略getter/setter
    ...
}

类B:

public class B {

    private Map<String, C> map;
    public static class C {

        private int a;

        private int b;

    }
    // 省略getter/setter
    ...
}

直接使用: BeanUtils.copyProperties(A,B); 获取map信息,Map<String, C> map = A.getMap(); 取map的value时会报错:比如A.C c = map.get("111");

java.lang.ClassCastException: B$C cannot be cast to A$C

原因

copyProperties方法在匹配时,只匹配了Map类型,就进行了赋值导致问题。

  Method readMethod = sourcePd.getReadMethod();
  if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
    ....
      
  }

解决方案

最简单的方式,遍历map赋值

Map<String,A.C> neoMap = Maps.newHashMap<>();
for (Map.Entry<String, B.C> c : map.entrySet()) {
    A.C ac = new A.C();
    BeanUtils.copyProperties(c.getValue(), ac);
    neoMap.put(c.getKey(), ac);
}

建议

只有同类型的才使用copyProperties方法