普通的序列化实现下Serializable接口就好了...
深入的没了解...
就记录下无聊测试时候发现的一个内部类序列化的事~
顺路测了下貌似可以一次序列化多个对象到单个文件里面而且读出来不会出错啊...
记得以前谁说会出错来着= =
package nest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 内部类的序列化测试
* */
public class NestClassSerialize {
public static void main(String[] args) throws IOException {
ObjectOutputStream oos;
oos = new ObjectOutputStream(
new FileOutputStream(new File("c:\\1.txt")));
// try {
// oos.writeObject(new Outer1().new Inner1());
// System.out.println("1");
// } catch (Exception e) {
// e.printStackTrace();
// }
// try {
// oos.writeObject(new Outer2.Inner2());
// System.out.println("2");
// } catch (Exception e) {
// e.printStackTrace();
// }
// try {
// oos.writeObject(new Outer3().new Inner3());
// System.out.println("3");
// } catch (Exception e) {
// e.printStackTrace();
// }
try {
oos.writeObject(new Outer4.Inner4());
System.out.println("4");
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("5");
oos.writeObject(new Outer5().new Inner5());
} catch (Exception e) {
e.printStackTrace();
}
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("c:\\1.txt")));
try {
System.out.println(ois.readObject());
System.out.println(ois.readObject());
// System.out.println(ois.readObject());//java.io.EOFException
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Outer1 implements Serializable {
public class Inner1 {
@Override
public String toString() {
return "外部类实现 + 普通内部类";
}
}
}
class Outer2 implements Serializable {
public static class Inner2 {
@Override
public String toString() {
return "外部类实现 + 静态内部类";
}
}
}
class Outer3 {
public class Inner3 implements Serializable {
@Override
public String toString() {
return "普通外部类 + 内部类实现";
}
}
}
class Outer4 {
public static class Inner4 implements Serializable {
@Override
public String toString() {
return "普通外部类 + 静态内部类实现";
}
}
}
class Outer5 implements Serializable {
public class Inner5 implements Serializable {
@Override
public String toString() {
return "外部类实现 + 内部类实现";
}
}
}
大概道理是这么个:
非静态内部类持有外部类引用,所以外部类一定也要实现Serializable接口
如果有错误的话请大侠指正~