我们知道被transient修饰的成员变量是不能够被序列化的,但是前面加上static修饰时,序列化及反序列化是没有问题的!测试的代码Foo.java和Test.java分别如下:
import java.io.Serializable;
class Foo implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -253787615565537985L;
public static int w = 1;
public static transient int x = 2;
public int y = 3;
public transient int z = 4;
}
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
Foo foo = new Foo();
System.out.printf("w: %d%n", Foo.w);
System.out.printf("x: %d%n", Foo.x);
System.out.printf("y: %d%n", foo.y);
System.out.printf("z: %d%n", foo.z);
try (FileOutputStream fos = new FileOutputStream("x.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(foo);
}
foo = null;
try (FileInputStream fis = new FileInputStream("x.ser");
ObjectInputStream ois = new ObjectInputStream(fis)) {
System.out.println();
foo = (Foo) ois.readObject();
System.out.printf("w: %d%n", Foo.w);
System.out.printf("x: %d%n", Foo.x);
System.out.printf("y: %d%n", foo.y);
System.out.printf("z: %d%n", foo.z);
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
}
}
}
运行结果如下所示:
w: 1
x: 2
y: 3
z: 4
w: 1
x: 2
y: 3
z: 0