實體類如何"不費力氣"的轉為Map
阿新 • • 發佈:2020-12-29
初衷:
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); }); }