BeanUtils.copyProperties()的使用
1、对象属性复制赋值(将 source 对象中与 target 对象中相同属性名的属性赋值):
BeanUtils.copyProperties(source, target);
演示:
首先定义两个类
LongDistanceBean 类:
public class LongDistanceBean{ /** * 用户ID */ private String userId; /** * 居住城市 */ private String liveCity; /** * 工作城市 */ private String workCity; /** * 工作电话 */ private String workPhone; /** * 构造器 */ public LongDistanceBean(String userId, String liveCity, String workCity, String workPhone) { this.userId = userId; this.liveCity = liveCity; this.workCity = workCity; this.workPhone= workPhone; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getLiveCity() { return liveCity; } public void setLiveCity(String liveCity) { this.liveCity = liveCity; } public String getWorkCity() { return workCity; } public void setWorkCity(String workCity) { this.workCity = workCity; } public String getWorkPhone() { return workPhone; } public void setWorkPhone(String workPhone) { this.workPhone = workPhone; } @Override public String toString() { return "LongDistanceBean{" + "userId='" + userId + '\'' + ", liveCity='" + liveCity + '\'' + ", workCity='" + workCity + '\'' + ", workPhone='" + workPhone + '\'' + '}'; } }
LocalBean 类:
public class LocalBean{ /** * 用户ID */ private String userId; /** * 居住城市 */ private String liveCity; /** * 工作城市 */ private String workCity; /** * 工作电话 */ private String workPhone; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getLiveCity() { return liveCity; } public void setLiveCity(String liveCity) { this.liveCity = liveCity; } public String getWorkCity() { return workCity; } public void setWorkCity(String workCity) { this.workCity = workCity; } public String getWorkPhone() { return workPhone; } public void setWorkPhone(String workPhone) { this.workPhone = workPhone; } @Override public String toString() { return "LocalBean{" + "userId='" + userId + '\'' + ", liveCity='" + liveCity + '\'' + ", workCity='" + workCity + '\'' + ", workPhone='" + workPhone + '\'' + '}'; } }
给类 LongDistanceBean 添加数据:
LongDistanceBeand longDistance= new LongDistanceBean("10001", "江西", "上海", "100-110-111");
执行以下代码:
public static void main(String[] args) { LongDistanceBean longDistance= new LongDistanceBean("10001", "江西", "上海", "100-110-111"); System.out.println(longDistance); LocalBean localBean= new LocalBean(); System.out.println(LocalBean); System.out.println("开始复制"); BeanUtils.copyProperties(longDistance, localBean); System.out.println(longDistance); System.out.println(localBean); }
Copy 结束,结果为:

浙公网安备 33010602011771号