序列化测试

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信息就是初始时的 信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值