【實體轉map】
阿新 • • 發佈:2019-01-26
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; /** * java實體轉成map * @author 宋志會 */ public class ObjAnalysis { private Integer id; private Integer miid; public Integer getMiid() { return miid; } public void setMiid(Integer miid) { this.miid = miid; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public static Map<String,Object> ConvertObjToMap(Object obj) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException{ Map<String,Object> reMap = new HashMap<String,Object>(); if (obj == null){ return null; } Field[] fields = obj.getClass().getDeclaredFields(); for(int i=0;i<fields.length;i++){ Field f = obj.getClass().getDeclaredField(fields[i].getName()); f.setAccessible(true); Object o = f.get(obj); reMap.put(fields[i].getName(), o); } return reMap ; } public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException { ObjAnalysis a = new ObjAnalysis(); a.setId(1111); a.setMiid(2222); Map<String,Object> m = ConvertObjToMap(a); System.out.println(m); } }