日期:2014-05-20 浏览次数:20806 次
public class ClassB{ //ClassB 不能序列化,因为没有实现Serializable接口 private String str; public ClassB(){ //default constructor } public ClassB(String str){ this.str = str; } }
import java.io.Serializable; public class ClassC implements Serializable{ private ClassB b; public ClassC(){ //default constructor } public ClassC(String str){ b = new ClassB(str); } public ClassB getClassB(){ return b; } }
import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.BufferedOutputStream; import java.io.BufferedInputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; public class Test{ public static void main(String[] args)throws Exception{ File file = new File("aa.bin"); ObjectOutputStream outStream = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(file))); outStream.writeObject(new ClassC("ricky")); outStream.close(); ObjectInputStream inStream = new ObjectInputStream( new BufferedInputStream( new FileInputStream(file))); inStream.readObject(); } }
---------- java ---------- Exception in thread "main" java.io.NotSerializableException: ClassB at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at Test.main(Test.java:15) 输出完成 (耗时: 3 秒) - 正常终止