Serializable接口中没有任何的方法。当一个类声明要实现Serializable接口时,只是表明该类参加串行化协议,而不需要实现任何特殊的方法。
注意:Thread类不能被并行化
import java.io.Serializable;
public class Goober implements Serializable {
private int width;
private String color;
private transient
long work;//若你的类中有不能并行化的或者不想并行化的成员,则使用transient进行忽略
Goober() {
width = 99;
color = "puce";
}
void setColor(String setting) {
color = setting;
}
String getColor() {
return(color);
}
}
========写=======
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SerialDemo1 {
public static void main(String arg[]) {
Goober goober = new Goober();
goober.setColor("magenta");
try {
FileOutputStream fos = new FileOutputStream("sergoob");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(goober);
oos.close();
} catch(IOException e) {
System.out.println(e);
}
}
}
========读=======
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class SerialDemo2 {
public static void main(String arg[]) {
Goober goober = null;
try {
FileInputStream fis = new FileInputStream("sergoob");
ObjectInputStream ois = new ObjectInputStream(fis);
goober = (Goober)ois.readObject();
ois.close();
} catch(IOException e) {
System.out.println(e);
} catch(ClassNotFoundException e) {
System.out.println(e);
}
String color = goober.getColor();
System.out.println(color);
}
}
本文详细解释了Java中Serializable接口的作用以及如何使用FileOutputStream和ObjectOutputStream进行对象的序列化和反序列化。重点介绍了如何在序列化过程中忽略特定成员变量,并通过实例演示了整个序列化与反序列化的过程。
696

被折叠的 条评论
为什么被折叠?



