您的位置:首页 > 其它

【反射机制】两个类名不同但其属性相同的对象,如何将一个对象的值赋给另外一个对象

2017-12-14 09:14 696 查看
最近公司需要用线程迁移一张表(业务表)的数据至另外一张表(备份表)中,两张表的字段一样,如何在程序中将查到的业务表数据集合转换到另外一个备份表数据集合中。

最初的想法,是新建一个一个的去赋值,但是这种方法后期如果表增加了字段将需要修改赋值的方法,舍弃了该方法。后来想到可以用反射的机制去进行赋值,下面是我的测试代码:(我们公司对象属性都是String类型)

public class ReflectDemo {

public static void main(String[] args) {
List<Drug> list=new ArrayList<Drug>();
List<DrugBk> bkList=new ArrayList<DrugBk>();
orgDrugData(list);//获取业务表数据
for(int i=0;i<list.size();i++){
Drug dTemp=list.get(i);
DrugBk dBk=new DrugBk();
convertObject(dTemp,dBk);//转换对象数据
bkList.add(dBk);
}

//  for(int i=0;i<bkList.size();i++){
//    System.out.println(bkList.get(i).getRecSn()+" "+bkList.get(i).getDrugName());
//}

}

public static void orgDrugData(List<Drug> list){
for(int i=0;i<10;i++){
Drug d=new Drug();
d.setRecSn(i+"");
d.setDrugCode("CODE_"+i);
d.setDrugName("药品_"+i);
list.add(d);
}
}

public static void convertObject(Object sourceObj,Object targetObj){
if (sourceObj == null || targetObj == null){
return;
}
Class targetClass = null;
Field[] sourceFields = null;
try{
targetClass = targetObj.getClass();
sourceFields = sourceObj.getClass().getDeclaredFields();
} catch (Exception e){
e.printStackTrace();
}

String fieldName = "";
Class fieldType = null;

for (int i = 0; i < sourceFields.length; i++){
try{
fieldName = sourceFields[i].getName();
fieldType = sourceFields[i].getType();
Field targetField = targetClass.getDeclaredField(fieldName);
if (targetField != null && targetField.getType().equals(fieldType)){
Method sourceGetter =getGetMethodName(fieldName,sourceObj);
Method targetSetter =getSetMethodName(fieldName,targetObj);
Object fieldValue = sourceGetter.invoke(sourceObj, null);
if (fieldValue != null){
targetSetter.invoke(targetObj, new Object[] { fieldValue });
}
}
} catch (NoSuchFieldException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}

public static Method getGetMethodName(String fieldName,Object obj) throws Exception{
try {
PropertyDescriptor pd = new PropertyDescriptor(fieldName,obj.getClass());
Method getMethod = pd.getReadMethod();//获得set方法
return getMethod;
} catch (IntrospectionException e) {
e.printStackTrace();
}
return null;
}

public static Method getSetMethodName(String fieldName,Object obj){
try {
PropertyDescriptor pd = new PropertyDescriptor(fieldName,obj.getClass());
Method setMethod = pd.getWriteMethod();//获得set方法
return setMethod;
} catch (IntrospectionException e) {
e.printStackTrace();
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐