實體轉換相關工具類

package com.zjx.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 實體工具類
 *
 * @author zhaojiaxing
 * @version 1.0
 * @since 2019年12月3日 上午11:02:29
 */

public class BeanUtil {
    /**
     * 兩個類相同屬性值複製並返回新對象
     *
     * @param source 複製源
     * @param clazz  目標類
     */
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source != null) {
            T t;
            try {
                t = clazz.newInstance();
                org.springframework.beans.BeanUtils.copyProperties(source, t);
                return t;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                return clazz.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 兩個類相同屬性值複製並返回新對象
     *
     * @param source 複製源
     * @param clazz  目標類
     * @return java.util.Optional<T>
     */
    public static <T> Optional<T> copyOptional(Object source, Class<T> clazz) {
        if (source != null) {
            T t;
            try {
                t = clazz.newInstance();
                org.springframework.beans.BeanUtils.copyProperties(source, t);
                return Optional.of(t);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Optional.empty();
    }

    /**
     * 兩個類相同屬性值複製並返回新對象
     *
     * @param sources 複製源
     * @param clazz   目標類
     */
    public static <T> List<T> copyList(List<?> sources, Class<T> clazz) {
        if (sources != null && sources.size() > 0) {
            List<T> items = new ArrayList<>();
            try {
                T t = null;
                for (Object source : sources) {
                    t = clazz.newInstance();
                    org.springframework.beans.BeanUtils.copyProperties(source, t);
                    items.add(t);
                }
                return items;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ArrayList<>();
    }

    /**
     * JSON 格式字符串轉換爲對象
     *
     * @param json  json格式字符串
     * @param clazz 對象
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        if (!StringUtils.isEmpty(json)) {
            return JSON.parseObject(json, clazz);
        }
        return null;
    }

    /**
     * JSON 格式字符串轉換爲對象集合
     *
     * @param jsonStr json格式字符串數組
     * @param clazz   對象
     */
    public static <T> List<T> parseList(String jsonStr, Class<T> clazz) {
        if (!StringUtils.isEmpty(jsonStr)) {
            List<T> result = new ArrayList<>();
            JSONArray array = JSONArray.parseArray(jsonStr);
            for (int i = 0; i < array.size(); i++) {
                result.add(JSON.toJavaObject((JSONObject) array.get(i), clazz));
            }
            return result;
        }
        return null;
    }

    /**
     * 獲取對象指定屬性值
     *
     * @param bean 目標對象
     * @param name 屬性名稱
     */
    public static String getProperty(Object bean, String name) {
        try {
            return BeanUtils.getProperty(bean, name);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * Object 數組轉換爲實體對象工具方法
     *
     * @param objs Object 數組
     * @param clz  實體類
     **/
    public static <T> T transEntity(Object[] objs, Class<T> clz) {
        T entity = null;
        try {
            // 獲取泛型實例
            entity = clz.newInstance();
            // 獲取所有屬性,按照屬性順序來賦值
            Field[] fields = clz.getDeclaredFields();
            for (int j = 0; j < fields.length; j++) {
                // 實時數據個數大於字段下標時賦值
                if (objs.length > j) {
                    // 解決 No value specified for 'Date'異常
                    ConvertUtils.register(new DateConverter(null), java.util.Date.class);
                    // 解決 No value specified for 'BigDecimal'異常
                    BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
                    BeanUtils.setProperty(entity, fields[j].getName(), objs[j]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }

    /**
     * 將map轉換爲實體類
     * 注意map的key必須爲實體的屬性名
     *
     * @param map
     * @param clz
     * @return: T
     * @author: zhaojiaxing
     * @createTime: 2019/10/23 0023 14:39
     */
    public static <T> T convertMap(Map map, Class<T> clz) {
        T entity = null;
        try {
            // 獲取泛型實例
            entity = clz.newInstance();
            // 獲取所有屬性,按照屬性順序來賦值
            Field[] fields = clz.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                // 獲取參數類型名字
                String filedTypeName = field.getType().getName();
                // 解決 No value specified for 'Date'異常
                ConvertUtils.register(new DateConverter(null), java.util.Date.class);
                // 解決 No value specified for 'BigDecimal'異常
                BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
                Object value = map.get(fieldName);
                // 判斷是否爲時間類型,使用equalsIgnoreCase比較字符串,不區分大小寫
                if (filedTypeName.equalsIgnoreCase("java.util.date")) {
                    String dateTimestamp = value.toString();
                    if (!dateTimestamp.equalsIgnoreCase("null")) {
                        value =  DateTimeUtil.strToDate(dateTimestamp,DateTimeUtil.YYYY_MM_DDHHMMSS);
                    }
                }
                BeanUtils.setProperty(entity, fieldName, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }


    /**
     * 數組對象轉實體集合工具方法
     *
     * @param items 數組對象
     * @param clz   實體類
     **/
    public static <T> List<T> transCollects(List<Object[]> items, Class<T> clz) {
        List<T> result = new ArrayList<>();
        try {
            if (null != items && items.size() > 0) {
                // 循環調用數組轉對象接口
                items.forEach(item -> result.add(transEntity(item, clz)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

發佈了94 篇原創文章 · 獲贊 94 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章