package com.itbuluoge.object; import java.io.Externalizable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; class Moon implements Externalizable{ public Moon() { System.out.println("moon"); } public void readExternal(ObjectInput arg0) throws IOException, ClassNotFoundException { // TODO Auto-generated method stub System.out.println("reading moon!"); } public void writeExternal(ObjectOutput arg0) throws IOException { // TODO Auto-generated method stub System.out.println("writing moon!"); } } class Sun implements Externalizable { Sun() { System.out.println("sun"); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // TODO Auto-generated method stub } public void writeExternal(ObjectOutput out) throws IOException { // TODO Auto-generated method stub } } public class Stars { public static void main(String[] args) throws Exception, IOException { Moon moon=new Moon(); Sun sun=new Sun(); ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("star.out")); o.writeObject(moon); o.writeObject(sun); o.close(); ObjectInputStream in=new ObjectInputStream(new FileInputStream("star.out")); moon=(Moon)in.readObject(); sun=(Sun)in.readObject(); in.close(); } }
我们能够看到输出结果
我们对moon的写和读序列化都没有问题,可是对sun的写没有问题,可是在读出的时候。抛出异常,由于实现了Externalizable接口的类,会调用构造函数,而sun的构造函数是私有的。无法訪问,从而导致抛出异常。