[자바 도구 클래스] 자바 빈 맵 도구 클래스

2398 단어 Java
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;
    }
}

좋은 웹페이지 즐겨찾기