objectUtil 构造model互转

package com.fyun.common.utils.util;
import com.fyun.common.utils.enums.EnumCopyField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class ObjectUtils {

    private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class);

    private ObjectUtils() {
    }

    public static <T> T build(Class<T> clazz, Object source) {
        if (null == clazz || null == source) return null;

        try {
            T target = clazz.newInstance();
            return build(source, target);
        } catch (Exception e) {
            logger.error("Object构造失败!", e);
        }
        return null;
    }

    public static <T, V> T buildMap(Class<T> clazz, Map<String, V> source) {
        if (null == clazz || null == source) return null;

        try {
            T target = clazz.newInstance();
            return buildMap(source, target);
        } catch (Exception e) {
            logger.error("Object构造失败!", e);
        }
        return null;
    }

    public static <T, V> List<T> buildBatchMap(Class<T> clazz, List<Map<String, V>> source) {
        if (null == clazz || null == source) return null;

        List<T> target = new ArrayList<T>();
        for (Map<String, V> s : source) {
            target.add(buildMap(clazz, s));
        }
        return target;
    }

    static class FieldModel {
        Field field;
        EnumCopyField copyField;

        public FieldModel(Field field, EnumCopyField copyField) {
            this.field = field;
            this.copyField = copyField;
        }
    }

    public static <T> T build(Object source, T target) {
        if (null == source || null == target) return null;

        try {
            Map<String, FieldModel> sourceMap = getAllFieldModels(source.getClass());
            Map<String, FieldModel> targetMap = getAllFieldModels(target.getClass());
            for (String key : targetMap.keySet()
                    ) {
                FieldModel tModel = targetMap.get(key);
                FieldModel sModel = sourceMap.get(key);
                if (sModel == null && tModel.copyField != null) {
                    sModel = sourceMap.get(tModel.copyField.fieldName());
                }
                if (sModel != null) {
                    Field t = tModel.field;
                    t.setAccessible(true);
                    Field s = sModel.field;
                    s.setAccessible(true);
                    if (s.get(source) == null)//资源对象为空结束本次循环
                        continue;
                    Object ob = null;
                    if (tModel.copyField == null && sModel.copyField == null) {
                        ob = s.get(source);
                    } else if (tModel.copyField != null) {
                        ob = doEnumCopy(t.getType(), tModel.copyField, sModel.field.get(source));
                    } else if (sModel.copyField != null) {
                        ob = doEnumCopy(t.getType(), sModel.copyField, sModel.field.get(source));
                    }
                    if (t.getType().isInstance(ob))
                        t.set(target, ob);
                }

            }
//            for (Map.Entry<String, Field> s : sourceMap.entrySet()) {
//                for (Map.Entry<String, Field> t : targetMap.entrySet()) {
//                    if (StringUtils.equals(s.getKey(), t.getKey())) {
//                        s.getValue().setAccessible(true);
//                        t.getValue().setAccessible(true);
//                        t.getValue().set(target, s.getValue().get(source));
//                    }
//                }
//            }
            return target;
        } catch (Exception e) {
            logger.error("Object构造失败!", e);
        }
        return null;
    }

    private static Object doEnumCopy(Class<?> targetType, EnumCopyField copyField, Object fValue
    ) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class classEnum = copyField.classEnum();
        String methodName = copyField.enumMethod();
        if (StringUtils.isEmpty(methodName))
            methodName = "valueOf";
        String enumFieldName = copyField.enumField();
        if (StringUtils.isEmpty(enumFieldName))
            enumFieldName = "name";

        if (targetType.isEnum() && fValue instanceof String) {
            Method method = classEnum.getDeclaredMethod(methodName, String.class);
            Object ob = method.invoke(null, fValue);
            return ob;
        } else if (fValue.getClass().isEnum()) {
            Method method = classEnum.getSuperclass().getDeclaredMethod(enumFieldName);
            return method.invoke(fValue);
        }
        return null;
    }

    public static <T, V> T buildMap(Map<String, V> source, T target) {
        if (null == source || null == target) return null;

        try {
            Map<String, Field> targetMap = getAllFields(target.getClass());
            for (Map.Entry<String, V> s : source.entrySet()) {
                for (Map.Entry<String, Field> t : targetMap.entrySet()) {
                    if ((StringUtils.equals(s.getKey(), t.getKey())
                            || StringUtils.equals(StringUtils.nderline2Camel(s.getKey()), t.getKey()))
                            && s.getValue().getClass() == t.getValue().getType()) {
                        t.getValue().setAccessible(true);
                        t.getValue().set(target, s.getValue());
                    }
                }
            }
            return target;
        } catch (Exception e) {
            logger.error("Object构造失败!", e);
        }
        return null;
    }

    private static Map<String, Field> getAllFields(Class clazz) {

        Map<String, Field> map = new HashMap<String, Field>();
        if (null == clazz || clazz == Object.class) return map;
        for (Field f : clazz.getDeclaredFields()) {
            if (!Modifier.isFinal(f.getModifiers()))
                map.put(f.getName(), f);
        }
        map.putAll(getAllFields(clazz.getSuperclass()));
        return map;
    }

    private static Map<String, FieldModel> getAllFieldModels(Class clazz) {

        Map<String, FieldModel> map = new HashMap<String, FieldModel>();
        if (null == clazz || clazz == Object.class) return map;
        for (Field f : clazz.getDeclaredFields()) {
            if (!Modifier.isFinal(f.getModifiers())) {
                EnumCopyField anField = f.getDeclaredAnnotation(EnumCopyField.class);
                FieldModel model = new FieldModel(f, anField);
                map.put(f.getName(), model);
                if (anField != null && StringUtils.isNotEmpty(anField.fieldName()) && !f.getName().equals(anField.fieldName()))
                    map.put(anField.fieldName(), model);
            }
        }
        map.putAll(getAllFieldModels(clazz.getSuperclass()));
        return map;
    }

    /**
     * @param entityClass
     * @param objects
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static <T> List<T> buildBatch(Class<T> entityClass, List objects) {
        List<T> list = new ArrayList<T>();
        for (Object object : objects) {
            T t = build(entityClass, object);
            if (null != t) {
                list.add(t);
            }
        }

        return list;
    }
}
原文地址:https://www.cnblogs.com/zrboke/p/12566275.html