1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| package com.tthk.inland.ticket.core.utils.other;
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map;
public class EntityUtils {
public static Map<String, Object> entityToMap(Object object) { Map<String, Object> map = new HashMap<>(); for (Field field : object.getClass().getDeclaredFields()) { try { boolean flag = field.isAccessible(); field.setAccessible(true); Object o = field.get(object); map.put(field.getName(), o); field.setAccessible(flag); } catch (Exception e) { e.printStackTrace(); } } return map; }
public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) { T t = null; try { t = entity.newInstance(); for (Field field : entity.getDeclaredFields()) { if (map.containsKey(field.getName())) { boolean flag = field.isAccessible(); field.setAccessible(true); Object object = map.get(field.getName()); if (object != null && field.getType().isAssignableFrom(object.getClass())) { field.set(t, object); } field.setAccessible(flag); } } return t; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return t; }
}
|