All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.cloud.kit.ObjectKit Maven / Gradle / Ivy

There is a newer version: 2.3.8.RELEASE
Show newest version
package com.feingto.cloud.kit;

import com.feingto.cloud.core.json.JSON;
import com.feingto.cloud.kit.reflection.ReflectionKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;

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

/**
 * 对象转换工具
 *
 * @author longfei
 */
@Slf4j
@SuppressWarnings({"unused", "unchecked", "WeakerAccess"})
public class ObjectKit {
    private static final String[] IGNORE_FIELD_NAMES = new String[]{"log", "logger", "serialVersionUID"};
    private static final String[] IGNORE_FIELD_CLASSES = new String[]{"org.apache.log4j.Logger", "org.slf4j.Logger", "org.slf4j.LoggerFactory", "java.kit.logging.Logger", "java.lang.Object", "java.lang.Class", "java.lang.reflect.AccessibleObject", "java.lang.reflect.Field", "java.lang.reflect.Method", "java.lang.reflect.Constructor"};

    /**
     * 序列化深度克隆
     *
     * @param bean Object
     * @return 
     */
    public static  T clone(Object bean) {
        return copy(bean, (Class) bean.getClass());
    }

    /**
     * 序列化深度复制
     *
     * @param bean  Object
     * @param clazz Class
     * @return 
     */
    public static  T copy(Object bean, Class clazz) {
        return JSON.build().json2pojo(JSON.build().obj2json(bean), clazz);
    }

    /**
     * 序列化深度复制到List
     *
     * @param bean  Object
     * @param clazz Class
     * @return 
     */
    public static  List copy2list(Object bean, Class clazz) {
        return JSON.build().json2list(JSON.build().obj2json(bean), clazz);
    }

    /**
     * 判断对象是否为空
     *
     * @param object Object
     * @return boolean
     */
    public static boolean isEmpty(Object object) {
        return object == null || object.getClass().isArray() && Array.getLength(object) == 0 ||
                object instanceof Collection && ((Collection) object).isEmpty() ||
                object instanceof Map && ((Map) object).isEmpty();
    }

    /**
     * 对象转换集合
     *
     * @param object Object
     * @return boolean
     */
    public static Collection objectToCollection(Object object) {
        if (object == null || object == "")
            return new ArrayList();

        Collection collection;
        if (object instanceof Collection) {
            collection = (Collection) object;
        } else if (object instanceof Map) {
            collection = ((Map) object).entrySet();
        } else if (object.getClass().isArray()) {
            collection = new ArrayList();
            int length = Array.getLength(object);
            for (int i = 0; i < length; i++) {
                Object value = Array.get(object, i);
                collection.add(value);
            }
        } else {
            collection = new ArrayList();
            collection.add(object);
        }
        return collection;
    }

    public static Object[] collectionToObject(Collection collection) {
        return collection.toArray(new Object[collection.size()]);
    }

    public static  T mapToObject(Class clazz, Map map) {
        try {
            T m = clazz.newInstance();
            BeanUtils.populate(m, map);
            return m;
        } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static  List mapToList(Class clazz, List> listMap) {
        List list = new ArrayList<>();
        for (Object map : listMap) {
            list.add(mapToObject(clazz, (Map) map));
        }
        return list;
    }

    public static boolean isIgnoreField(Field field) {
        return field != null && (isIgnoreFieldByName(field) || isIgnoreFieldByClass(field));
    }

    private static boolean isIgnoreFieldByName(Field field) {
        for (String fieldName : IGNORE_FIELD_NAMES) {
            if (fieldName.equals(field.getName()))
                return true;
        }
        return field.getName().contains("this$");
    }

    private static boolean isIgnoreFieldByClass(Field field) {
        Class clazz;
        for (String className : IGNORE_FIELD_CLASSES) {
            clazz = ReflectionKit.forName(className);
            if (clazz != null && clazz.isAssignableFrom(field.getType()))
                return true;
        }
        return false;
    }

    public static String toString(Object obj) {
        if (obj == null) {
            return "null";
        } else {
            Class clazz = obj.getClass();
            if (!clazz.equals(Object.class) && !clazz.equals(Class.class)) {
                if (ClassKit.isJavaBasicType(clazz)) {
                    return obj.toString();
                } else {
                    StringBuilder sb = new StringBuilder();
                    if (clazz.isArray()) {
                        if (ClassKit.isPrimitiveArray(clazz)) {
                            Object[] objs = new Object[]{obj};
                            sb.append(clazz.getSimpleName()).append("=");
                            String objsStr = Arrays.deepToString(objs);
                            sb.append(objsStr.substring(1, objsStr.length() - 1));
                            return sb.toString();
                        } else {
                            return toString(obj);
                        }
                    } else if (Collection.class.isAssignableFrom(clazz)) {
                        return toString(obj);
                    } else if (Map.class.isAssignableFrom(clazz)) {
                        return toString(obj);
                    } else {
                        sb.append(clazz.getSimpleName()).append("{");
                        Field[] fields = ClassKit.getAllField(clazz);
                        if (fields.length > 0) {
                            boolean isAppend = false;
                            AccessibleObject.setAccessible(fields, true);
                            for (Field field : fields) {
                                if (!isIgnoreField(field)) {
                                    isAppend = true;
                                    sb.append(field.getName()).append("=");
                                    try {
                                        sb.append(toString(field.get(obj))).append(",");
                                    } catch (Exception var10) {
                                        sb.append("???,");
                                    }
                                }
                            }
                            if (isAppend) {
                                sb.deleteCharAt(sb.length() - 1);
                            }
                        }
                        sb.append("}");
                        return sb.toString();
                    }
                }
            } else {
                return obj.toString();
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy