最终瞬态字段的序列化/反序列化 [英] Serialization/Deserialization of the final transient fields

查看:67
本文介绍了最终瞬态字段的序列化/反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题中,该问题表示 final transient 字段不能设置为任何非默认值.那么,为什么我对 aVar1 变量有3个,而对 aVar3 变量则有s3?

In this question says that final transient fields can not be set to any non-default value after serialization. So why I have 3 for aVar1 variable and s3 for aVar3 variable?

import java.io.*;
import java.util.*;

class Test
{
    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        A a1 = new A();
    
        // save a1 to file
        FileOutputStream fileOutput = new FileOutputStream("a.dat");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutput);
        outputStream.writeObject(a1);
        fileOutput.close();
        outputStream.close();
    
        // load a1 from file
        FileInputStream fiStream = new FileInputStream("a.dat");
        ObjectInputStream objectStream = new ObjectInputStream(fiStream);
        a1 = (A) objectStream.readObject();
        fiStream.close();
        objectStream.close();
    
        // fields after deserialization
        System.out.println(a1.aVar1); // 3
        System.out.println(a1.aVar2); // null
        System.out.println(a1.aVar3); // s3
        System.out.println(a1.aVar4); // null
    }
}

class A implements Serializable
{
    public final transient int aVar1 = 3;
    public final transient Map <Object, Object>  aVar2 = new HashMap <> ();
    public final transient String aVar3 = "s3";
    public final transient String aVar4 = new String("s4");
}

推荐答案

在反序列化过程中,未调用对象的构造函数.这是由JVM处理的特殊对象实例化过程.

During deserialization, the constructor of the object is not called. This is a special object instantiation process handled by the JVM.

对于aVar2和aVar4,将调用Hashmap和字符串构造函数.因此,这些变量被分配了默认值(空).

For aVar2 and aVar4, the Hashmap and string constructor is called. So these variables are assigned default values(null).

对于aVar1和aVar3,为其分配了一些常量表达式.这些称为编译时间常数.

For aVar1 and aVar3, some constant expression is assigned to them. These are called compile time constants.

编译时间常数的条件是

  1. 必须将它们声明为最终的
  2. 它们是原始数据类型或String
  3. 必须使用声明对其进行初始化.
  4. 它们的值必须是常量表达式.

编译时间常数会受影响,反序列化后这些值将保留.

Compile time constants are reaffected and these values will be retained after deserialisation.

这篇关于最终瞬态字段的序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆