通过反射的方式将同名属性值进行传递

public class TransValUtils {

    /**
     * 对象相同属性copy
     *
     * @param origin
     * @param traget
     * @throws Exception 转换报错
     */
    public static void cloneObj(Object  origin, Object traget) {
        if (origin == null) {
            return;
        }
        try {

            Field[] tragetFields = traget.getClass().getDeclaredFields();
            Field[] originFields = origin.getClass().getDeclaredFields();
            for (Field tragetfield : tragetFields) {
                for (Field originField : originFields){
                    if(tragetfield.getName().equals(originField.getName()) &&
                            tragetfield.getType().getName().equals(originField.getType().getName())){
                        tragetfield.set(traget,originField.get(origin));
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/ltian123/p/14085433.html