Serializable接口
java.io.Serializable 接口没有方法或字段,仅用于标识可序列化的语义。
public interface Serializable {
}
可序列化类的所有子类型本身都是可序列化的。在进行序列化操作时,会判断要被序列化的类是否是Enum
、Array
和 Serializable
类型,如果都不是则直接抛出NotSerializableException
。
@Data
public class A1_User implements Serializable {
private String name;
private int age;
}
A1_User user = new A1_User();
user.setName("xiaoming");
user.setAge(18);
序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(user);
反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("tempFile")));
A1_User newUser = (A1_User) ois.readObject();
Externalizable接口
public interface Externalizable extends java.io.Serializable {
void writeExternal(ObjectOutput out) throws IOException;
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}
需要重写writeExternal()与readExternal()方法。否则所有变量的值都会变成默认值。
重写就会很灵活,可以随意加减属性
@Data
public class B1_User implements Externalizable {
private String name;
private int age;
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeInt(age);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
age = in.readInt();
}
}
B1_User user = new B1_User();
user.setName("xiaoming");
user.setAge(18);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(user);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("tempFile")));
B1_User newUser = (B1_User) ois.readObject();
两种序列化的对比
实现Serializable接口 | 实现Externalizable接口 |
---|---|
所有属性自动都会被序列化,简单但死板 | 需要重写writeExternal()与readExternal()方法,啰嗦但灵活 |
性能略差 | 性能略好 |
必须要提供一个public的无参的构造器 |