超轻量级对象复制转换-比dozer快100倍

来源:互联网 发布:sai for mac 无压感 编辑:程序博客网 时间:2024/04/29 16:11

之前项目里面一直在用dozer,后来遇到性能瓶颈问题,一查看发现dozer复制一个对象居然用了0.2秒尴尬  看来是不能用了,dozer 虽然强大,但我用的都只是很简单的功能,就对象的复制转换,于是就自己用反射写了个复制方法,结果发现性能提升了好多好多。。


话不多说,上代码,下面是方法的代码:

    /**     *     * @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;    }


附录一张我自己测试的结果图:




0 0
原创粉丝点击