SerializationUtil.java
package util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; /** * 序列化工具类 * * @author Logen * */ public class SerializationUtil { /** * 序列化对象 * * @param obj 对象 * @return 序列化后的字节数组 */ public static byte[] serialization(Object obj) { if (null == obj) { return null; } byte[] bytes = null; ByteArrayOutputStream byteArrayOutputStream = null; ObjectOutputStream out = null; try { byteArrayOutputStream = new ByteArrayOutputStream(); out = new ObjectOutputStream(byteArrayOutputStream); out.writeObject(obj); bytes = byteArrayOutputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != byteArrayOutputStream) { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return bytes; } /** * 反序列化 * * @param bytes 对象序列化后的字节数组 * @return 反序列化后的对象 */ public static Object deserialization(byte[] bytes) { if (null == bytes) { return null; } Object obj = null; ObjectInputStream in = null; ByteArrayInputStream byteArrayInputStream = null; try { byteArrayInputStream = new ByteArrayInputStream(bytes); in = new ObjectInputStream(byteArrayInputStream); obj = in.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != byteArrayInputStream) { try { byteArrayInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return obj; } /** * 反序列化成指定类型的对象 * * @param bytes 对象序列化后的字节数组 * @param c 反序列化后的对象类型 * @return 指定类型的对象 */ public static <T> T deserialization(byte[] bytes, Class<T> c) { return c.cast(deserialization(bytes)); } public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("name", "Logen"); map.put("age", 26); byte[] bytes = serialization(map); Map<?, ?> map2 = deserialization(bytes, Map.class); System.out.println(map2.get("name")); System.out.println(map2.get("age")); } }
.