在Java中序列化对象时,静态变量的值是否会被保存?
在Java中,序列化是一个可以将对象的状态写入字节流的概念,以便我们可以通过网络传输它(使用JPA和RMI等技术)。
要序列化一个对象:
- 确保类实现了Serializable接口。
- 创建一个表示要将对象存储到的文件的**FileOutputStream**对象(抽象路径)。
- 通过传递上面创建的**FileOutputStream**对象来创建一个ObjectOutputStream对象。
- 使用writeObject()方法将对象写入文件。
要反序列化一个对象:
- 创建一个表示包含序列化对象的**FileInputStream**对象。
- 使用readObject()方法从文件中读取对象。
- 使用检索到的对象。
反序列化对象中的变量
当我们反序列化一个对象时,只有实例变量会被保存,并且在处理后将具有相同的值。
瞬态变量 - 瞬态变量的值永远不会被考虑(它们被排除在序列化过程之外)。也就是说,当我们声明一个变量为瞬态变量时,反序列化后的值将始终为null、false或零(默认值)。
静态变量 - 静态变量的值在反序列化过程中不会被保留。事实上,静态变量也不会被序列化,但由于它们属于类。反序列化后,它们会从类中获取它们当前的值。
示例
在这个程序中,我们在反序列化类之前更改了类的实例、静态和瞬态变量的值。
处理之后,实例变量的值将相同。瞬态变量显示默认值,静态变量显示来自类的新的(当前)值。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable{
private String name;
private transient int age;
private static int year = 2018;
public Student(){
System.out.println("This is a constructor");
this.name = "Krishna";
this.age = 25;
}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Year: "+Student.year);
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setYear(int year) {
Student.year = year;
}
}
public class SerializeExample{
public static void main(String args[]) throws Exception{
//Creating a Student object
Student std = new Student("Vani", 27);
//Serializing the object
FileOutputStream fos = new FileOutputStream("e:\student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(std);
oos.close();
fos.close();
//Printing the data before de-serialization
System.out.println("Values before de-serialization");
std.display();
//Changing the static variable value
std.setYear(2019);
//Changing the instance variable value
std.setName("Varada");
//Changing the transient variable value
std.setAge(19);
System.out.println("Object serialized.......");
//De-serializing the object
FileInputStream fis = new FileInputStream("e:\student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student deSerializedStd = (Student) ois.readObject();
System.out.println("Object de-serialized.......");
ois.close();
fis.close();
System.out.println("Values after de-serialization");
deSerializedStd.display();
}
}输出
Values before de-serialization: Name: Vani Age: 27 Year: 2018 Object serialized....... Object de-serialized....... Values after de-serialization: Name: Vani Age: 0 Year: 2019
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP