芝麻_糊

导航

两个对象的属性赋值

public class BeanCopyUtil {
    private static final Log log = LogFactory.getLog("FILE-ERROR");
    public static void copyField(Object targetObj, Object orginObj){
        if(targetObj == null || orginObj == null){
            log.error("BeanCopyUtil 属性拷贝的工具类出现null.[targetObj:"+targetObj+"]-[orginObj:"+orginObj+"]");
            return;
        }
        Class targetClass = targetObj.getClass();
//        Field[] orgFields = orginObj.getClass().getFields();
//        if(orgFields.length ==0){
        Field[] orgFields = orginObj.getClass().getDeclaredFields();
//        }
        for (Field orgField : orgFields) {
            Field targetField;
            try {
                targetField = targetClass.getDeclaredField(orgField.getName());
            } catch (Exception e) {
                continue;
            }
            if (targetField != null) {
                targetField.setAccessible(true);
                orgField.setAccessible(true);
                try {
                    targetField.set(targetObj, orgField.get(orginObj));
                } catch (Exception e) {
                    continue;//当出现NoSuchFieldException异常时,直接下一次循环,这样就将origin中有的filed而target中没有的filed忽略
                } finally {
                    targetField.setAccessible(false);
                    orgField.setAccessible(false);
                }
            }
        }
    }

 

posted on 2017-11-02 15:09  芝麻_糊  阅读(374)  评论(0编辑  收藏  举报