欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java对象转MAP

程序员文章站 2022-04-02 10:17:45
package com.test.example;import com.alibaba.fastjson.JSON;import lombok.AllArgsConstructor;import lombok.Builder;import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescript....
package com.test.example;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Builder;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class MapExample {

    public static void main(String[] args) {
        Student student=Student.builder()
                .name("xuyi")
                .address("henan")
                .age(18)
                .build();
        Map<String,Object> map= toMap(student);
        System.out.println(JSON.toJSONString(map));
    }

    public static Map<String, Object> toMap(Object bean) {
        Objects.requireNonNull(bean, "Bean cannot be null");

        Class type = bean.getClass();
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo info = Introspector.getBeanInfo(type);
            PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : descriptors) {
                String propertyName = descriptor.getName();
                switch (propertyName) {
                    case "class":
                    case "pageIndex":
                    case "pageSize":
                        continue;
                }
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean);
                if (!Objects.isNull(result)) {
                    map.put(propertyName, result);
                }
            }
        } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }
}

@AllArgsConstructor
@Builder
class Student{
    private String name;
    private int age;
    private String address;
}

 

本文地址:https://blog.csdn.net/weixin_42548604/article/details/114263788

相关标签: java