gpt4 book ai didi

java - 原始类型的 transient final 和 transient final 包装类型之间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:24 32 4
gpt4 key购买 nike

transient final inttransient final Integer 有什么不同。

使用 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

使字段成为 transient 将阻止其序列化,但有一个异常(exception):

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 JLS 15.28. 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 - 原始类型的 transient final 和 transient final 包装类型之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25304468/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com