作者:微信小助手
发布时间:2021-10-06T08:08:57
Serializbale
接口」不就好了的状态,直到 ...
Student
类对象序列化到一个名为
student.txt
的文本文件中,然后再通过文本文件反序列化成
Student
类对象:
public class Student implements Serializable {
private String name;
private Integer age;
private Integer score;
@Override
public String toString() {
return "Student:" + 'n' +
"name = " + this.name + 'n' +
"age = " + this.age + 'n' +
"score = " + this.score + 'n'
;
}
// ... 其他省略 ...
}
public static void serialize( ) throws IOException {
Student student = new Student();
student.setName("CodeSheep");
student.setAge( 18 );
student.setScore( 1000 );
ObjectOutputStream objectOutputStream =
new ObjectOutputStream( new FileOutputStream( new File("student.txt") ) );
objectOutputStream.writeObject( student );
objectOutputStream.close();
System.out.println("序列化成功!已经生成student.txt文件");
System.out.println("==============================================");
}
public static void deserialize( ) throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream =
new ObjectInputStream( new FileInputStream( new File("student.txt") ) );
Student student = (Student) objectInputStream.readObject();
objectInputStream.close();
System.out.println("反序列化结果为:");
System.out.println( student );
}
序列化成功!已经生成student.txt文件
==============================================
反序列化结果为:
Student:
name = CodeSheep
age = 18
score = 1000
Student
类时,实现了一个
Serializable
接口,然而当我们点进
Serializable
接口内部查看,发现它竟然是一个空接口,并没有包含任何方法!
Student
类时忘了加
implements Serializable
时会发生什么呢?
NotSerializableException
异常:
ObjectOutputStream
的
writeObject0()
方法底层一看,才恍然大悟:
Serializable
接口的话,在序列化时就会抛出
NotSerializableException
异常!
Serializable
接口也仅仅只是做一个标记用!!!
Serializable
接口的类都是可以被序列化的!然而真正的序列化动作不需要靠它完成。
serialVersionUID
号有何用?serialVersionUID
的字段:
private static final long serialVersionUID = -4392658638228508589L;
serialVersionUID
的序列号?
Student
类为例,我们并没有人为在里面显式地声明一个
serialVersionUID
字段。
serialize()
方法,将一个
Student
对象序列化到本地磁盘上的
student.txt
文件:
public static void serialize() throws IOException {
Student student = new Student();
student.setName("CodeSheep");
student.setAge( 18 );
student.setScore( 100 );
ObjectOutputStream objectOutputStream =
new ObjectOutputStream( new FileOutputStream( new File("student.txt") ) );
objectOutputStream.writeObject( student );
objectOutputStream.close();
}
Student
类里面动点手脚,比如在里面再增加一个名为
studentID
的字段,表示学生学号:
student.txt
文件,还用如下代码进行反序列化,试图还原出刚才那个
Student
对象:
public static void deserialize( ) throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream =
new ObjectInputStream( new FileInputStream( new File("student.txt") ) );
Student student = (Student) objectInputStream.readObject();
objectInputStream.close();
System.out.println("反序列化结果为:");
System.out.println( student );
}