public class SerializationUtil {
public static byte[] serialize(Person person) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(person);
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Person deserialize(byte[] bytes) {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
return (Person) ois.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
Person person = new Person("Alice", 30);
// 序列化
byte[] serializedPerson = SerializationUtil.serialize(person);
System.out.println("Serialized person: " + serializedPerson);
// 反序列化
Person deserializedPerson = SerializationUtil.deserialize(serializedPerson);
System.out.println("Deserialized person: " + deserializedPerson);
}
}
确保所有的可序列化类都实现了 Serializable 接口。
处理异常时要小心,特别是 ClassNotFoundException,它可能会在反序列化时抛出。
使用 try-with-resources 语句来确保流被正确关闭。
java序列化
最新推荐文章于 2024-08-30 18:40:43 发布