java – 基本类型的瞬态最终和瞬态最终包装类型之间的区别

瞬态最终int和瞬态最终整数之间有什么不同.

使用int:

transient final int a = 10;

序列化之前:

a = 10

序列化后:

a = 10

使用整数:

transient final Integer a = 10;

序列化之前:

a = 10

序列化后:

a = null

完整代码

public class App implements Serializable {
    transient final Integer transientFinal = 10;

    public static void main(String[] args) {
    try {
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
                "logInfo.out"));
        App a = new App();
        System.out.println("Before Serialization ...");
        System.out.println("transientFinalString = " + a.transientFinal);
        o.writeObject(a);
        o.close();
    } catch (Exception e) {
        // deal with exception
        e.printStackTrace();
    }

    try {

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                "logInfo.out"));
        App x = (App) in.readObject();
        System.out.println("After Serialization ...");
        System.out.println("transientFinalString = " + x.transientFinal);
    } catch (Exception e) {
        // deal with exception
                    e.printStackTrace();
    }
}

}

解决方法

文章中所述

http://www.xyzws.com/Javafaq/can-transient-variables-be-declared-as-final-or-static/0

使字段瞬态将阻止其序列化,但有一个例外:

There is just one exception to this rule,and it is when the transient final field member is initialized to a constant expression as those defined in the 07001. Hence,field members declared this way would hold their constant value expression even after deserializing the object.

如果您将访问提到的JSL,您就会知道

A constant expression is an expression denoting a value of primitive type or a String

但是Integer不是原始类型,它不是String,因此它不被视为常量表达式的候选者,因此它的值在序列化后不会保留.

演示:

class SomeClass implements Serializable {
    public transient final int a = 10;
    public transient final Integer b = 10;
    public transient final String c = "foo";

    public static void main(String[] args) throws Exception {

        SomeClass sc = new SomeClass();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(sc);

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
                bos.toByteArray()));
        SomeClass sc2 = (SomeClass) ois.readObject();

        System.out.println(sc2.a);
        System.out.println(sc2.b);
        System.out.println(sc2.c);
    }
}

输出

10
null
foo

相关文章

ArrayList简介:ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增...
一、进程与线程 进程:是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位。 线程...
本文为博客园作者所写: 一寸HUI,个人博客地址:https://www.cnblogs.com/zsql/ 简单的一个类...
#############java面向对象详解#############1、面向对象基本概念2、类与对象3、类和对象的定义格式4、...
一、什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错。在java中,阻止当前方法或作用域...
Collection接口 Collection接口 Collection接口 Collection是最基本的集合接口,一个Collection代表一组...