FieldsMapper.java 1.3 KB
Newer Older
frank.xa.zhang's avatar
frank.xa.zhang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
package pwc.taxtech.atms.dto;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

public class FieldsMapper {
    private static Logger LOGGER = LoggerFactory.getLogger(FieldsMapper.class);

    /**
     * 将source对象的属性填充到destination对象对应属性中
     *
     * @param source      原始对象
     * @param destination 目标对象
     */
    public static <S, D> void map(S source, D destination) throws ClassNotFoundException, IllegalAccessException {
        Class clsDestination = Class.forName(destination.getClass().getName());
        Class clsSource = Class.forName(source.getClass().getName());

        Field[] declaredFields = clsDestination.getDeclaredFields();

        for (Field field : declaredFields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            try {
                if ("serialVersionUId".equals(fieldName)) {
                    continue;
                }
                Field sourceField = clsSource.getDeclaredField(fieldName);
                sourceField.setAccessible(true);
                field.set(destination, sourceField.get(source));

            } catch (NoSuchFieldException e) {
                LOGGER.warn("NoSuchFieldException {}", fieldName);
            }
        }
    }

}