如果我们有两个不同的类对象,但他们具有相同的属性,我们怎么将一个对象的属性值复制给另外一个对象呢?
我们可以利用反射完成这个需求:首先我们利用反射得到两个对象的所有属性,再通过循环得到源对象(被复制的对象)每个属性值,然后再将值复制给目标对象(复制的对象)的属性。
源对象的类:
public class UserSource {
private String name;
private int age;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}目标对象的类:
public class UserTarget {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
接下来,就是复制属性的操作代码:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CopyProperties {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
UserSource source = new UserSource();
UserTarget target = new UserTarget();
source.setAge(23);
source.setName("hao");
source.setAddress("gd");
copy(source, target);
System.out.println("Name:" + target.getName());
System.out.println("Age:" + target.getAge());
}
/**
* 复制源对象和目标对象的属性值
*
*/
public static void copy(Object source, Object target) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class sourceClass = source.getClass();//得到对象的Class
Class targetClass = target.getClass();//得到对象的Class
Field[] sourceFields = sourceClass.getDeclaredFields();//得到Class对象的所有属性
Field[] targetFields = targetClass.getDeclaredFields();//得到Class对象的所有属性
for(Field sourceField : sourceFields){
String name = sourceField.getName();//属性名
Class type = sourceField.getType();//属性类型
String methodName = name.substring(0, 1).toUpperCase() + name.substring(1);
Method getMethod = sourceClass.getMethod("get" + methodName);//得到属性对应get方法
Object value = getMethod.invoke(source);//执行源对象的get方法得到属性值
for(Field targetField : targetFields){
String targetName = targetField.getName();//目标对象的属性名
if(targetName.equals(name)){
Method setMethod = targetClass.getMethod("set" + methodName, type);//属性对应的set方法
setMethod.invoke(target, value);//执行目标对象的set方法
}
}
}
}
}
执行结果:
Name:hao Age:23
原文:http://blog.csdn.net/angelwings_hao/article/details/39478395