关于对象序列化小例子的2个小问题。
请看注释问题。
import java.io.*;
public class ObjectTest implements Serializable {
static private int a; //问题1:static 和 transient的字段不是不能序列化的吗?(这在jdk ObjectOutputStream类中有说过)
static String s;
//public ObjectTest(){System.out.println("Constructor");} //问题2:我把默认的构造器注释起来居然也能运行(这在jdk Serializable接口中有说过)
public ObjectTest(int a, String s){
this.a = a;
this.s = s;
}
//private void writeObject(java.io.ObjectOutputStream out)throws IOException{
//out.writeInt(a);
//out.writeObject(s);
//}
//
//private void readObject(java.io.ObjectInputStream in)throws IOException,ClassNotFoundException{
//a = in.readInt();
//s = (String)in.readObject();
//}
public String toString(){
return "a = " + a + ", s = " + s;
}
public static void main(String[] args)throws IOException, ClassNotFoundException{
ObjectTest ot = new ObjectTest(1, "a");
System.out.println("Test one:");
System.out.println(ot);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("D:\\333\\OOO.test"));
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(ot);
oos.close();
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("D:\\333\\OOO.test"));
ObjectInputStream ois = new ObjectInputStream(bis);
ObjectTest ot2 = (ObjectTest)ois.readObject();
ois.close();
System.out.println("Test two:");
System.out.println(ot2);
}
}
import java.io.*;import java.util.*;public class Test implements Serializable{ public transient int a; public Test(){ } public static void main(String[] args) { Test t = new Test(); t.a = 10; System.out.println("t.a = " + t.a); try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("t.dat")); out.writeObject(t); out.close(); ObjectInputStream in = new ObjectInputStream(new FileInputStream("t.dat")); Test nt = (Test)in.readObject(); in.close(); System.out.println("nt.a = " + nt.a); } catch(Exception e){e.printStackTrace();} }}
[解决办法]
第一个问题。static 和 transient的字段事实上并没有序列化。
反序列化输出的是类的值。
如果该成这样
oos.close();[color=#FF0000]ObjectTest.a=2;[/color] BufferedInputStream bis = new BufferedInputStream( new FileInputStream("D:\\333\\OOO.test"));
[解决办法]
static的数据没有被序列化。之所以你的测试看起来好像是被序列化了,原因是static的数据在内存中使用都是只有一份,你把代码改称下面这样子
public static void main(String[] args)throws IOException, ClassNotFoundException{
ObjectTest ot = new ObjectTest(1, "a");
System.out.println("Test one:");
System.out.println(ot);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("D:\\333\\OOO.test"));
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(ot);
oos.close();
ot.a = 99;
ot.s = "bluesmile979";
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("D:\\333\\OOO.test"));
ObjectInputStream ois = new ObjectInputStream(bis);
ObjectTest ot2 = (ObjectTest)ois.readObject();
ois.close();
System.out.println("Test two:");
System.out.println(ot2);
}
或者把read程序单独做一个类,单独执行。就能看到效果了
至于默认构造函数的问题,你写不写java好像都会自动加上一个没有参数什么都不做的构造函数。具体自己去查一下,既不太清楚了。
[解决办法]