加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:02:09 所属栏目: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
瞬态最终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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读