反射机制-对象复制转换

/** 
 * 
 * @param obj       转换源对象 
 * @param toObj     转换类型 
 * @param <T>       转换结果 
 * @return 
 * @throws Exception 
 */  
private <T> T objSimpleConvert(Object obj,Class<T> toObj)throws Exception{  
    T toObjIns = (T)toObj.newInstance(); //创建目标对象实例  
    Class sourCls = obj.getClass();  
    //遍历源属性  
    do{  
        Field[] sourFlds = sourCls.getDeclaredFields(); //源属性集  
        for(int i = 0 ; i < sourFlds.length; i++){ //遍历源所有属性  
            Field sf = sourFlds[i];  
            sf.setAccessible(true);  
              System.out.println(sf.getName());  
            //遍历目标所有属性  
            Class toCls = toObj;  
            do{  
                Field[] toFlds = toCls.getDeclaredFields(); //源属性集  
                for(int j = 0 ; j < toFlds.length; j++){ //遍历源所有属性  
                    Field tof = toFlds[j];  
                    tof.setAccessible(true);  
                    if(sf.getName().equals(tof.getName())){ //属性名字相同  
                        String type = tof.getType().toString();//得到此属性的类型  
                        if (type.endsWith("String")) {  
                            tof.set(toObjIns,(String)sf.get(obj));  
                        }else if(type.endsWith("int") || type.endsWith("Integer")){  
                            tof.set(toObjIns,(Integer)sf.get(obj));  
                        }else if(type.endsWith("Date")){  
                            tof.set(toObjIns,(Date)sf.get(obj));  
                        }else if(type.endsWith("long") || type.endsWith("Long")){  
                            tof.set(toObjIns,(Long)sf.get(obj));  
                        }else if(type.endsWith("short") || type.endsWith("Short")){  
                            tof.set(toObjIns,(Short)sf.get(obj));  
                        }else {  
                            log.error("类型转换失败!");  
                            throw new Exception("类型转换失败!");  
                        }  
                    }  
                }  
                toCls = toCls.getSuperclass();  
  
            }while(toCls != Object.class);  
        }  
        sourCls = sourCls.getSuperclass();  
    }while(sourCls != Object.class);  
    return toObjIns;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值