有时候我们的两个对象字段都是一样的,只有极少的区别,想要把一个对象字段的值,赋值给另外一个对象值

然后传给另外一个方法使用,但是这个字段太多,一个一个的复制太过繁琐。

这时候利用反射解决这个问题。

class TestObject1{
private Integer age;
private String name;
//特有的字段
private String weight;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
} }
class TestObject2{
private Integer age;
private String name;
//特有的字段
private String address;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
} }

编写test测试类

public class Test {

    /**
* origin字段向target转化
* @param origin
* @param target
* @return
*/
public static <T> T swap(Object origin,T target){
Field[] tFs = target.getClass().getDeclaredFields();//获得属性
Field[] oFs = origin.getClass().getDeclaredFields();//获得属性
for(int i=0;i<tFs.length;i++){
String tname=tFs[i].getName();
for(int j=0;j<oFs.length;j++){
if(oFs[j].getName().equals(tname)){
Object val=getValue(origin, tname);
setValue(target, tname, val);
}
}
}
return target;
}
/**
*
* @param beanObj 实体类
*/
private static Object getValue(Object beanObj,String name){
try {
Field[] fields = beanObj.getClass().getDeclaredFields();//获得属性
Class clazz = beanObj.getClass();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String names=field.getName();
if(!names.equals(name)){
continue;
}
// 此处应该判断beanObj,property不为null
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
if (getMethod != null) {
//System.out.println(beanObj+"的字段是:"+field.getName()+",类型是:"+field.getType()+",取到的值是: "+getMethod.invoke(beanObj));
return getMethod.invoke(beanObj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
*
* @param beanObj 实体类
* @param name 字段名
* @param value 值
*/
private static void setValue(Object beanObj,String name,Object value){
try {
Field[] fields = beanObj.getClass().getDeclaredFields();//获得属性
Class clazz = beanObj.getClass();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String names=field.getName();
if(!names.equals(name)){
continue;
} PropertyDescriptor pd = new PropertyDescriptor(field.getName(), beanObj.getClass());
Method setMethod = pd.getWriteMethod();
if (setMethod != null) {
setMethod.invoke(beanObj, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} }

编写main方法

 public static void main(String[] args) {
TestObject1 test1=new TestObject1();
test1.setAge(22);
test1.setName("gys");
TestObject2 test2=swap(test1,new TestObject2());
System.out.println(test2.getName()); }