1. 程式人生 > 實用技巧 >JAVA 實體類List<Entity >轉 List<Map>

JAVA 實體類List<Entity >轉 List<Map>

public static <T extends IdEntity> List<Map<Object,Object>> EntityConvertMap(List<T> list){
   List<Map<Object,Object>> l = new LinkedList<>();
   try {
      for(T t : list){
         Map<Object,Object> map = new HashMap<>();
         Method[] methods 
= t.getClass().getMethods(); for (Method method : methods) { if (method.getName().startsWith("get")) { String name = method.getName().substring(3); name = name.substring(0, 1).toLowerCase() + name.substring(1); Object value = method.invoke(t);
if(method.getGenericReturnType().toString().equals("class java.util.Date")&&value!=null){ value = getNow((Date)value, "yyyy-MM-dd HH:mm:ss"); } map.put(name,value); } } l.add(map); } } catch (Exception e) { e.printStackTrace(); }
return l; }

2.//list實體類轉換成map
public static List<Map<String,Object>> EntityConvertMap(List<Dept> list){
List<Map<String,Object>> l = new LinkedList<>();
try {
for(Dept t : list){
Map<String,Object> map = new HashMap<>();
Method[] methods = t.getClass().getMethods();
for (Method method : methods) {
if (method.getName().startsWith("get")) {
String name = method.getName().substring(3);
name = name.substring(0, 1).toLowerCase() + name.substring(1);
Object value = method.invoke(t);
map.put(name,value);
}
}
l.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
return l;
}