package cn.autoform.util.tool; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * 对象转换工具类 * @ClassName: ObjectTools * @author [九鼎联合科技] * @date 2017年5月12日 下午1:00:24 */ public class ObjectTool { /** * 对象转byte * @param obj * @return */ public static byte[] objectToByte(Serializable obj) { if(Objects.isNull(obj)){ return null; } byte[] bytes = null; try ( ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo)){ oo.writeObject(obj); bytes = bo.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return bytes; } /** * byte转对象 * @param bytes * @param clazz * @return */ @SuppressWarnings("unchecked") public static T byteToObject(byte[] bytes, Class clazz) { if(Objects.isNull(bytes)) { return null; } T obj = null; ByteArrayInputStream bi = new ByteArrayInputStream(bytes); ObjectInputStream oi = null; try { oi = new ObjectInputStream(bi); } catch (IOException e) { return null; } try { obj = (T) oi.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; } /** * 转前 * [Object,Object,Object,Object] * 转后 * [Map,Map,Map,Map] * @param objs * @return * @throws IllegalAccessException */ public static List> toMapColl(Collection objs) throws IllegalAccessException{ List> list = new ArrayList<>(objs.size()); for (Object obj : objs) { list.add(toMapObj(obj)); } return list; } /** * 转前 * Object * 转后 * Map * @param obj * @return * @throws IllegalAccessException */ public static Map toMapObj(Object obj) throws IllegalAccessException{ Class clazz = obj.getClass(); Map map = new HashMap<>(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String fieldName = field.getName(); Object fieldVal = field.get(obj); if(fieldVal instanceof Collection){ fieldVal = toMapColl((Collection)fieldVal); } if(null != fieldVal) map.put(fieldName, fieldVal); } return map; } }