需求:两个对象中有相同类型相同名称的属性,把一个对象中的属性值复制到另一个对象。
方法1:
org.springframework.beans.BeanUtils#copyProperties(java.lang.Object, java.lang.Object);
该方法只能对一个bean中普通属性字段进行copy,如果这个bean中有其他的bean,即bean中bean,就需要将其值取出,单独对这个子bean进行copy,然后set进父bean,这种copy如果在bean层次少的时候还无所谓,如果在bean的层次比较深的时候,就会发现很是繁琐了
方法2:
实体类:
Customer类
/** * @Author lucky * @Date 2022/1/4 10:28 */ @Slf4j @Builder @Data public class Customer { private String name; private int age; private String gender; private Map<String,String> params; private Map<String,String> heads; }
User类:
@Data @Builder @Slf4j @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String gender; private Map<String,String> params; }
工具类:
/** * @Author lucky * @Date 2022/1/4 10:14 */ @Slf4j public class BeanCopyUtils { public static <T> void beanCopyProperties(T src, T dest){ Map<String,Object> properties=new HashMap<>(); Arrays.stream(src.getClass().getDeclaredFields()).forEach((field -> { try { field.setAccessible(true); properties.put(field.getName(), field.get(src)); } catch (IllegalAccessException e) { //log.error("",e ); } })); populateBean(dest,dest.getClass(),properties); populateBean(dest,dest.getClass().getSuperclass(),properties); } private static <T> void populateBean(T bean,Class clazz,Map<String,Object> properties){ Arrays.stream(clazz.getDeclaredFields()).forEach((field -> { try { field.setAccessible(true); //如果非空,覆盖原有值;如果为空,则不覆盖原有值 if(properties.get(field.getName())!=null){ field.set(bean,properties.get(field.getName())); } } catch (IllegalAccessException e) { //log.error("",e); } })); } public static void main(String[] args) { Map<String,String> params=new HashMap<>(); params.put("userInfo","ttbank 2021"); Customer customer = Customer.builder().age(26).gender("man").params(params).build(); //01 使用自己创建的工具类 User user=new User(); user.setName("lucky"); beanCopyProperties(customer, user); System.out.println(user); params.put("userInfo","ttbank 2022"); System.out.println(user); System.out.println(customer); //02 使用工具类BeanUtils User user2=new User(); BeanUtils.copyProperties(customer,user2); System.out.println(user2); } }
控制台输出:
User(name=lucky, age=26, gender=man, params={userInfo=ttbank 2021}) User(name=lucky, age=26, gender=man, params={userInfo=ttbank 2022}) Customer(name=null, age=26, gender=man, params={userInfo=ttbank 2022}, heads=null) User(name=null, age=26, gender=man, params={userInfo=ttbank 2022})
参考文献:
https://blog.csdn.net/qq_37276508/article/details/102366097