`

序列化测试

阅读更多
import java.io.*;

class Student implements Serializable {
	private String name;
	private transient String password;
	private static int count = 0;

	public Student(String name, String password) {
		System.out.println("调用Student的带参的构造方法");
		this.name = name;
		this.password = password;
		count++;
	}

	public String toString() {
		return "人数: " + count + " 姓名: " + name + " 密码: " + password;
	}
}

public class ObjectSerTest1 {
	public static void main1(String args[]) {
		try {

			FileOutputStream fos = new FileOutputStream("test.obj");
			ObjectOutputStream oos = new ObjectOutputStream(fos);

			Student s1 = new Student("张三", "12345");
			Student s2 = new Student("王五", "54321");

			oos.writeObject(s1);
			oos.writeObject(s2);

			oos.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		try {
			FileInputStream fis = new FileInputStream("test.obj");
			ObjectInputStream ois = new ObjectInputStream(fis);

			Student s3 = (Student) ois.readObject();
			Student s4 = (Student) ois.readObject();

			System.out.println(s3);
			System.out.println(s4);

			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 静态成员属于类级别的,所以不能序列化
这里的不能序列化的意思,是序列化信息中不包含这个静态成员域
你这个测试成功,是因为你都在同一个机器(而且是同一个进程),因为你这个jvm已经把count加载进来了,所以你获取的是加载好的count,如果你 是传到另一台机器或者你关掉程序重写写个程序读入test.obj,此时因为别的机器或新的进程是重新加载count的,所以count信息就是初始时的 信息。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics