java通过反射将对象A得属性值赋值给对象B
java通过反射将对象A得属性值赋值给对象B
//测试类1
public class Test1 {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//测试类2
public class Test2 {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//测试代码
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class AppTest {
public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InstantiationException, SecurityException, NoSuchFieldException {
Test1 target = new Test1();// 目标对象
Test2 copyEd = new Test2(); //被复制的对象
copyEd.setAge(32);
copyEd.setName("你好");
target = (Test1) copyObject(target,copyEd);
System.out.println(target.getName());
System.out.println(target.getAge());
System.out.println(target.getSex());
}
/**
* 将被复制对象的属性值,复制给目标目标对象
* @param target 目标对象
* @param copyObj 被复制对象
* @return
* @throws ClassNotFoundException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchFieldException
未考虑属性类型不一致得情况。以及未考虑属性为类得情况
*/
public static <T> Object copyObject(Object target , Object copyObj) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InstantiationException, SecurityException, NoSuchFieldException{
// Object o = Class.forName(clzzName).newInstance();
Object o = target.getClass().newInstance();
Class tClz = target.getClass();
Class cClz = copyObj.getClass();
Map<String,Object> field_Val = new HashMap<String,Object>();
/**获取被复制对象的值,放入map,key为属性名称,value为属性值*/
for(Field f : cClz.getDeclaredFields()){
String fieldName = f.getName();
f.setAccessible(true);
field_Val.put(fieldName, f.get(copyObj));
// System.out.println(method+" "+f.get(copyObj));
}
for(Field tf : tClz.getDeclaredFields()){
String fieldName = tf.getName();
Object targetV = field_Val.get(fieldName);
if(targetV==null){
continue;
}
tf.setAccessible(true);
tf.set(o, targetV);
}
return o;
}
}

浙公网安备 33010602011771号