JAVA复制对象属性

看到好多两个对象相同对象补全的,但是不符合我最常用的需求,于是写了一个方法,用于两个对象间的相同类型(或子类)字段的补全,两个对象无需是相同类型,没加锁不支持并发合并同一对象.

import javax.management.OperationsException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author gaokuo 相似对象复制
 **/
public class SameEntityClone {

    /**
     * 相同类型,相同名称的字段复制,会直接
     * @param from 原始对象
     * @param to 接收
     * @param cover 是否覆盖原有参数
     * @throws Exception 异常  不支持的操作或者其他
     */
    public static void deal(Object from,Object to,boolean cover) throws Exception {
        if (from == null || to == null){
            return;
        }
        if (from == to) {
            throw new OperationsException("相同的目标");
        }
        Class fromC = from.getClass();
        Class toC = to.getClass();
        Field[] fromFields = fromC.getDeclaredFields();
        Field[] toFields = toC.getDeclaredFields();
        if (fromFields.length == 0 || toFields.length == 0) {
            return;
        }
        for (Field fromField : fromFields) {
            fromField.setAccessible(true);
            for (Field toField : toFields) {
                if (Modifier.isFinal(toField.getModifiers())){
                    continue;
                }
                toField.setAccessible(true);
                if (toField.getType().isAssignableFrom(fromField.getType())  && fromField.getName().equals(toField.getName())) {
                    if (cover && fromField.get(from) != null) {
                        toField.set(to, fromField.get(from));
                    } else {
                        if (toField.get(to) == null) {
                            toField.set(to, fromField.get(from));
                        }
                    }
                }
            }
        }
    }

    /**
     * 相同类型,相同名称的字段复制,不覆盖原有参数
     * @param from 原始对象
     * @param to 接收
     * @throws Exception 异常  不支持的操作或者其他
     */
    public static void deal(Object from,Object to) throws Exception {
        deal(from,to,false);
    }

    /**
     * 相同类型,相同名称的字段复制  这个方法会返回一个新建对象
     * @param from 原始对象
     * @param toC 接收类型
     * @throws Exception 异常  不支持的操作或者其他
     */
    public static T deal(Object from,Class toC) throws Exception {
        T to = toC.newInstance();
        deal(from,to,false);
        return to;
    }

}


你可能感兴趣的:(java)