java的日常开发经常会出现对象属性拷贝赋值的场景,比较常见的解决方式是使用org.springframework.beans.BeanUtils的copyProperties类。该类能够通过反射机制来获取源对象和目的对象的属性,并将对应的属性值进行复制,从而减少手动编写属性复制代码的工作量,提高代码的可读性和维护性。然而在使用过程中,需要注意以下几种情况会导致属性复制失效:
1. 类型不匹配
@Data
public class SourceBean {
private Long age;
}
@Data
public class TargetBean {
private String age;
}
public class Test {
public static void main(String[] args) {
SourceBean source = new SourceBean();
source.setAge(25L);
TargetBean target = new TargetBean();
BeanUtils.copyProperties(source, target);
System.out.println(target.getAge()); //拷贝赋值失败,输出null
}
}
2. 属性名称不一致
public class SourceBean {
private String username;
}
public class TargetBean {
private String userName;
}
SourceBean source = new SourceBean();
source.setUsername("捡田螺的小男孩");
TargetBean target = new TargetBean();
BeanUtils.copyProperties(source, target);
System.out.println(target.getUserName()); // 输出为 null
3. Null 值覆盖
@Data
public class SourceBean {
private String name;
private String address;
}
@Data
public class TargetBean {
private String name;
private String address;
}
SourceBean source = new SourceBean();
source.setName("John");
source.setAddress(null);
TargetBean target = new TargetBean();
target.setAddress("田螺address");
BeanUtils.copyProperties(source, target);
System.out.println(target.getAddress()); // 输出为 null
4. Boolean类型数据+is属性开头的坑
@Data
public class SourceBean {
private boolean isTianLuo;
}
@Data
public class TargetBean {
private Boolean isTianLuo;
}
SourceBean source = new SourceBean();
source.setTianLuo(true);
TargetBean target = new TargetBean();
BeanUtils.copyProperties(source, target);
System.out.println(target.getIsTianLuo()); // 输出为 null