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修饰的字段不会被序列化。