com.alibaba.schedulerx.worker.util.SerializationUtil Maven / Gradle / Ivy
package com.alibaba.schedulerx.worker.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Java自带的序列化机制,对象必须实现Serializable
*
* @author xiaomeng.hxm
*/
public class SerializationUtil {
// 将对象序列化为字节数组
public static byte[] serialize(Object obj) throws IOException {
try (ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutStream = new ObjectOutputStream(byteOutStream)) {
objectOutStream.writeObject(obj);
return byteOutStream.toByteArray();
}
}
// 将字节数组反序列化为对象
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream byteInStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInStream = new ObjectInputStream(byteInStream)) {
return objectInStream.readObject();
}
}
}