Java對象序列化的方法有以下幾種:
public class MyClass implements Serializable {
// ...
}
public class MyClass implements Externalizable {
@Override
public void writeExternal(ObjectOutput out) throws IOException {
// ...
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// ...
}
}
// 序列化
MyClass obj = new MyClass();
try (FileOutputStream fileOut = new FileOutputStream("file.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(obj);
}
// 反序列化
try (FileInputStream fileIn = new FileInputStream("file.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
MyClass obj = (MyClass) in.readObject();
}
// 序列化為JSON字符串
MyClass obj = new MyClass();
String json = new Gson().toJson(obj);
// 反序列化為Java對象
MyClass obj = new Gson().fromJson(json, MyClass.class);
需要注意的是,如果一個類的父類實現了Serializable接口,則子類自動實現了Serializable接口。同時,被transient修飾的字段不會被序列化。