老师您好,我发现在测试Student类的静态字段是否可以被序列化时,如果在Test类main方法中先调用write(),再调用read()方法,静态字段schoolName可以被打印出来;但是如果先write()执行完程序,再把write()注释掉,执行read()方法,静态字段schoolName值为null。请问是为什么呢?
源代码如下:
Student类
package com.realive.testSequence;
import java.io.Serializable;
/**
* @author Realive
* @Student.java
* @2019年4月10日
*/
public class Student implements Serializable{
private String name;
private int age;
public static String schoolName;
private transient String pwd;//该属性的值不被序列化
/**
*
*/
public Student() {
super();
// TODO Auto-generated constructor stub
}
/**
* @param name
* @param age
* @param pwd
*/
public Student(String name, int age, String pwd) {
super();
this.name = name;
this.age = age;
this.pwd = pwd;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", pwd=" + pwd + ", schoolName="
+schoolName +"]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
Test类
package com.realive.testSequence;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author Realive
* @Test.java
* @2019年4月10日
*/
public class Test {
public static void main(String[] args) {
write();
read();
}
public static void write() {
ObjectOutputStream oos =null;
try {
oos = new ObjectOutputStream(new FileOutputStream("E:\\student.txt"));
Student stu = new Student("marry",20,"888888");
Student.schoolName = "桂柳小学";//这一行为静态成员变量赋值
oos.writeObject(stu);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//关闭
if(oos!=null) {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void read() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("E:\\student.txt"));
Student stu = (Student)ois.readObject();
System.out.println(stu);
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(ois!=null) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
write();read();同时执行时,输出结果为:Student [name=marry, age=20, pwd=null, schoolName=桂柳小学]
先只执行一次write(),再只执行一次read(),输出结果为:Student [name=marry, age=20, pwd=null, schoolName=null]
请问是为什么呢?
是否可以理解为write()方法创建的Student对象,在write()方法结束调用后,因为对象并没有消失,所以read()方法反序列化Student对象时先在内存中根据对象序列化ID(或者其他标识?)查找对象,如果没有该ID对应的对象存在时才将使用从磁盘文件中反序列化对象进来,实际上read()方法反序列化得对象还是内存中的那个Student对象,读取的是该对象对应堆中的对象信息(name、age、pwd)以及方法区常量池中的静态字段(schoolName)?