java两个类之间copy部分属性

BeanUtils.copyProperties(to, from); 是全部属性copy类似于覆盖


private static void copyProperties(Object o1, Object o2) {



String fileName,str,getName,setName;
List fields = new ArrayList();
Method getMethod = null;
Method setMethod = null;
try {
Class c1 = o1.getClass();
Class c2 = o2.getClass();

Field[] fs1 = c1.getDeclaredFields();
Field[] fs2 = c2.getDeclaredFields();
//两个类属性比较剔除不相同的属性,只留下相同的属性
for(int i = 0;i < fs2.length;i++) {
for(int j = 0;j < fs1.length;j++) {
if(fs1[j].getName().equals(fs2[i].getName())) {
fields.add(fs1[j]);
break;
}
}
}
if(null != fields && fields.size() > 0){
for (int i = 0;i < fields.size();i++) {
//获取属性名称
Field f = (Field) fields.get(i);
fileName = f.getName();
//属性名第一个字母大写
str = fileName.substring(0, 1).toUpperCase();
//拼凑getXXX和setXXX方法名
getName = "get" + str + fileName.substring(1);
setName = "set" + str + fileName.substring(1);
//获取get、set方法
getMethod = c1.getMethod(getName, new Class[]{});
           setMethod = c2.getMethod(setName, new Class[]{f.getType()});
           
           //获取属性值
           Object o = getMethod.invoke(o1, new Object[]{});
           System.out.println(fileName + " : " + o);
           //将属性值放入另一个对象中对应的属性
           if(null != o) {
            System.out.println("o2.setMethod = " + setMethod);
            setMethod.invoke(o2, new Object[] {o});
           }
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值