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

您所在的位置:网站首页 怎么将实体类转化为map 实体类如何"不费力气"的转为Map

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

2023-11-10 12:17| 来源: 网络整理| 查看: 265

  初衷:

    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 getAllMethods(Object obj) { List methods = new ArrayList();     // 获取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 convert2Map(Object obj) { Map map = new HashMap(); List 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 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);// 将 实体类 转换为 MapMap map = JSON.parseObject(JSON.toJSONString(person), Map.class);System.out.println(map);



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3