【Java工具类】JavaBean转Map工具类

import com.alibaba.fastjson.annotation.JSONField;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MapUtils {

    /**
     * object to map
     *
     * @param object
     * @return
     */
    public static Map toMap(Object object) {
        Map map = new HashMap<>(16);
        if (object == null) {
            return map;
        }

        try {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field == null || field.getName() == null) {
                    continue;
                }
                field.setAccessible(true);
                String key = field.getName();
                JSONField jsonField = field.getDeclaredAnnotation(JSONField.class);
                if (jsonField != null) {
                    key = jsonField.name();
                }
                map.put(key, field.get(object));
            }
        } catch (IllegalAccessException e) {
            log.info("object to map convert exception", e);
        }
        return map;
    }

    /**
     * object to map
     *
     * @param object
     * @param ignore
     * @return
     */
    public static Map toMap(Object object, boolean ignore) {
        Map map = new HashMap<>(16);
        if (object == null) {
            return map;
        }

        try {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field == null || field.getName() == null) {
                    continue;
                }
                field.setAccessible(true);
                if (ignore && field.get(object) == null) {
                    continue;
                }
                String key = field.getName();
                JSONField jsonField = field.getDeclaredAnnotation(JSONField.class);
                if (jsonField != null) {
                    key = jsonField.name();
                }
                map.put(key, field.get(object));
            }
        } catch (IllegalAccessException e) {
            log.info("object to map convert exception", e);
        }
        return map;
    }
}

你可能感兴趣的:(Java)