@Slf4j
public class ObjectSerializeUtil {
//序列化
public static byte[] getObjectByteArray(Object o) {
//将对象序列化成字节数组
ByteArrayOutputStream ba = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(ba);
//用对象序列化流来将对象o序列化,然后把序列化之后的二进制数据写到字节流ba中
oos.writeObject(o);
} catch (IOException e) {
log.error("", e);
}
//通过字节流返回字节数组
return ba.toByteArray();
}
//反序列化
public static Object getObject(byte[] bytes) {
//将byte数据反序列出对象
if (bytes != null) {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
try {
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
} catch (IOException | ClassNotFoundException e) {
log.error("", e);
}
}
return null;
}
}