1、引入apache jar 包,如下:
commons-beanutils-1.7.0.jar
commons-logging.jar
2、
User u1 = new User();
u1.setAge(10);
u1.setPassword("22222");
u1.setUserName("王黄");
u1.setD(1.0f);
ToUser u2 = new ToUser();
try {
BeanUtils.copyProperties(u2, u1);
//PropertyUtils.copyProperties(u2, u1);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
BeanUtils和PropertyUtils进行对象复制时,都是将后边的对象的属性值复制给前面的对象。
BeanUtils和PropertyUtils复制对象时,根据属性名进行复制。
如果属性名相同,但类型不同,BeanUtils会直接转换。而PropertyUtils会直接抛出异常。
3、代码:
(1)
package com.test;
public class User {
private String userName;
private String password;
private Integer age;
private Float d;
public Float getD() {
return d;
}
public void setD(Float d) {
this.d = d;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
(2)
package com.test;
public class ToUser {
private String userName;
private String password;
private Integer age;
private String d;
public String getD() {
return d;
}
public void setD(String d) {
this.d = d;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
(3)
package com.test;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
public class CopyClass {
public static void main(String[] args) {
User u1 = new User();
u1.setAge(10);
u1.setPassword("22222");
u1.setUserName("王黄");
u1.setD(1.0f);
ToUser u2 = new ToUser();
try {
BeanUtils.copyProperties(u2, u1);
//PropertyUtils.copyProperties(u2, u1);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(u1.getD().getClass());
System.out.println(u2.getD().getClass());
}
}