是的,Serializable 接口没有任何方法可以实现。如果你想序列化对象,你的对象必须实现 Serializable 接口。接下来,您可以对对象执行序列化/反序列化过程,例如使用 ObjectOutputStream 和 ObjectInputStream 对象。
例子很少。
类,需要序列化/反序列化:
import java.io.Serializable;
public class ObjectToSerialize implements Serializable {
private static final long serialVersionUID = 7526472295622776147L;
private String firstName;
private String lastName;
public ObjectToSerialize(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public String toString() {
return getFirstName() + " " + getLastName();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ObjectToSerialize that = (ObjectToSerialize) o;
return firstName.equals(that.firstName) && lastName.equals(that.lastName);
}
}
具有序列化/反序列化方法的类:
import java.io.*;
public class ObjectSerialization {
public static void saveObject(Serializable object, String path) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
oos.writeObject(object);
}
}
public static Object loadObject(String path) throws ClassNotFoundException, IOException {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) {
return ois.readObject();
}
}
public static void main(String[] args) {
ObjectToSerialize object = new ObjectToSerialize("Eldar", "Agalarov");
try {
String path = "C:/object.bin";
saveObject(object, path);
System.out.println("Object serialized: " + object);
ObjectToSerialize deserializedObject = (ObjectToSerialize) loadObject(path);
System.out.println("Object deserialized: " + deserializedObject);
System.out.println("They are equals: " + object.equals(deserializedObject));
} catch (Exception e) {
e.printStackTrace();
}
}
}
另请阅读有关序列化的本指南