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

前端之家收集整理的这篇文章主要介绍了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

猜你在找的Java相关文章