一个对象只要实现了Serilizable接口,这个对象就可以被序列化,Java的这种序列化模式为开发者提供了很多便利,我们可以不必关系具体序列化的过程,只要这个类实现了Serilizable接口,这个的所有属性和方法都会自动序列化。
如果我们一个实现Serilizable接口的类中的某个属性不需要序列化,可以用 transient类标识这个属性,这样这个属性在反序列化是并不会被加载进来,例如
public class TestTransient {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
A a = new A(25,"张三");
System.out.println(a);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c://mm.txt"));
oos.writeObject(a);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c://mm.txt"));
a = (A)ois.readObject();
System.out.println(a);
}
}
class A implements Serializable{
int a;
transient String b;
public A(int a,String b){
this.a = a;
this.b = b;
}
public String toString(){
return "a = "+a+",b = "+b;
}
}
运行结果如下:
a = 25,b = 张三
a = 25,b = null