实体类如何"不费力气"的转为Map

  初衷:

    db返回了一个实体类,想封装成一个Map留着按需获取属性,所以就有了下面的Utils

 

    

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

/**
 * @program: ht
 * @description: 实体类存入Map
 * @author: Wangly
 * @create: 2020-12-29 13:29
 * @version: 1.0.0
 */
public class BeanMap {
    /**
     * 获取obj中的所有方法
     * 
     * @param obj
     * @return
     */
    public List<Method> getAllMethods(Object obj) {
        List<Method> methods = new ArrayList<Method>();
     // 获取obj字节码 Class<?> clazz = obj.getClass(); while (!clazz.getName().equals("java.lang.Object"))
      {
       // 获取方法 methods.addAll(Arrays.asList(clazz.getDeclaredMethods())); clazz = clazz.getSuperclass(); } return methods; } /** * 将一个类用属性名为Key,值为Value的方式存入map * * @param obj * @return */ public Map<String, Object> convert2Map(Object obj) { Map<String, Object> map = new HashMap<String, Object>(); List<Method> methods = getAllMethods(obj); for (Method m : methods) { String methodName = m.getName(); if (methodName.startsWith("get")) { // 获取属性名 String propertyName = methodName.substring(3); try { map.put(propertyName, m.invoke(obj)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } return map; } }

  Test

  测试实体类

import lombok.Data;

/**
 * @program: ht
 * @description: TestBeanMap
 * @author: Wangly
 * @create: 2020-12-29 13:37
 * @version: 1.0.0
 */
@Data
public class Person {
    private int id;
    private String name;
    private String nipples;
    private String sw;
    private String bra;
    private String foot;
    private String mouth;

    public Person() {}

    public Person(int id, String name, String nipples, String sw, String bra, String foot, String mouth) {
        this.id = id;
        this.name = name;
        this.nipples = nipples;
        this.sw = sw;
        this.bra = bra;
        this.foot = foot;
        this.mouth = mouth;
    }
}

  测试类

 

@Test
    public void BeanMapTest() {
        BeanMap beanMap = new BeanMap();
        Person p = new Person();
        p.setId(1);
        p.setBra("pink");
        p.setMouth("good");
        p.setNipples("pink");
        p.setSw("black");
        p.setFoot("good");

        Map<String, Object> stringObjectMap = beanMap.convert2Map(p);
        stringObjectMap.forEach((k, v) -> {
            System.out.println("k:" + k + ",v:" + v);
        });
    }

  输出

  发现多少沾点多此一举   避免重复造轮子

 

// 将 Map 转换为 实体类
Person person = JSON.parseObject(JSON.toJSONString(personMap), person.class);
System.out.println(user);
// 将 实体类 转换为 Map
Map map = JSON.parseObject(JSON.toJSONString(person), Map.class);
System.out.println(map);

posted on 2020-12-29 14:08  王半仙儿的博客  阅读(3162)  评论(0编辑  收藏  举报

导航