Bean熟悉替换,只替换部分属性,其他属性值不改变
需要加入:asm.jar cglib-2.1.jar,用来map和bean之间的转换(比spring和反射的效率好,因为加入了缓存)
package com.bean.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.cglib.beans.BeanMap; public class CopyBean { /** * @param args */ public static void main(String[] args) { User u1 = new User(); u1.setId(1); u1.setName("用户1"); u1.setPwd("12333"); u1.setAddress("杭州西湖区"); GirlFriend girl11 = new GirlFriend("范冰冰"); GirlFriend girl12 = new GirlFriend("林心如"); List<GirlFriend> list1 = new ArrayList<GirlFriend>(); list1.add(girl11); list1.add(girl12); u1.setGirls(list1); User u2 = new User(); u2.setName("【用户222】"); u2.setAddress("【-甘肃省兰州市-】"); GirlFriend girl21 = new GirlFriend("【赵雅芝】"); GirlFriend girl22 = new GirlFriend("【张柏芝】"); GirlFriend girl32 = new GirlFriend("【汤唯】"); List<GirlFriend> list2 = new ArrayList<GirlFriend>(); list2.add(girl21); list2.add(girl22); list2.add(girl32); u2.setGirls(list2); copyBean(u1, u2); System.out.println("拷贝后:"+u1); }
}
拷贝的方法:
/** * 将对象中需要改变的属性值 拷贝到目标对象中,替换目标对象中的部分属性值 * * @param fromBean 要改变的对象 * @param targetBean 目标对象 */ public static void copyBean(Object fromBean, Object targetBean) { Map<String, Object> fromMap = beanToMap(fromBean); Map<String, Object> toMap = beanToMap(targetBean); for (String key : fromMap.keySet()) { if (fromMap.get(key) == null) { continue; } //将fromMap的值设置到toMap中 toMap.put(key, fromMap.get(key)); } //转换map为bean mapToBean(toMap, targetBean); } /** * 将对象装换为map * * @param bean * @return */ public static Map<String, Object> beanToMap(Object bean) { Map<String, Object> map = new HashMap<String, Object>(); if (bean != null) { BeanMap beanMap = BeanMap.create(bean); for (Object key : beanMap.keySet()) { map.put(key + "", beanMap.get(key)); } } return map; } /** * 将map装换为javabean对象 * * @param map * @param bean * @return */ public static void mapToBean(Map<String, Object> map, Object bean) { BeanMap beanMap = BeanMap.create(bean); beanMap.putAll(map); }
结果:
from:{id=0, girls=[GirlFriend [name=【赵雅芝】], GirlFriend [name=【张柏芝】], GirlFriend [name=【汤唯】]], pwd=null, address=【-甘肃省兰州市-】, name=【用户222】} to:{id=1, girls=[GirlFriend [name=范冰冰], GirlFriend [name=林心如]], pwd=12333, address=杭州西湖区, name=用户1} 拷贝后:User [编号=1, 姓名=【用户222】, 密码=12333, 地址=【-甘肃省兰州市-】, 女朋友=[GirlFriend [name=【赵雅芝】], GirlFriend [name=【张柏芝】], GirlFriend [name=【汤唯】]]]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16968.html