请教一个对象序列化问题:哪些field在序列化时会被写入stream中?

在查看java.io.ObjectOutputStream.writeObject(Object obj)方法的注释时,看到这句说明

Write the specified object to the ObjectOutputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are written.

大致意思是:
将指定的对象写入到ObjectOutputStream中。有关这个对象的类的信息、类的签名、该类的非transient和 非static的属性的值,以及该对象所有的父类都被写入ObjectOutputStream。

按照这个说明,non-static属性的值不会被写入,但在下面的例子中,static属性的值是被写入了的。

我想,这个应该是注释说明的错误吧?请教一下各位。


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 Foo implements Serializable {
	private String name = "My name is foo.";
	private static String desc = "I will still be here!";
	private transient String abandoned = "I will be abandoned!";
	
	public Foo(){}
	
	public String toString(){
		StringBuilder result = new StringBuilder();
		result.append(name);
		result.append("-");
		result.append(desc);
		result.append("-");
		result.append(abandoned);
		return result.toString();
	}
	
	public static void main(String[] args) throws ClassNotFoundException, IOException{
		Foo foo = new Foo();
		System.out.println("foo = " + foo);
		
		ObjectOutputStream out = new ObjectOutputStream(
				new FileOutputStream("foo.out"));
		out.writeObject("Foo storage\n");
		out.writeObject(foo);
		out.close();
		
		ObjectInputStream in = new ObjectInputStream(
				new FileInputStream("foo.out"));
		String s = (String)in.readObject();
		Foo foo2 = (Foo)in.readObject();
		System.out.println(s + "foo2 = " + foo2);
		in.close();		
	}
}



输出结果:
foo = My name is foo.-I will still be here!-I will be abandoned!
foo2 = My name is foo.-I will still be here!-null


你可能感兴趣的:(jvm,jdk)