java 如果将成员数据声明为原始数据类型,如果对象声明为可序列化,值是否会被序列化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6327324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:24:05  来源:igfitidea点击:

If declaring member data as primitive data types, will values be serialized if object is declared serializable?

javaserializationwrapperprimitive

提问by Oh Chin Boon

i have a question on whether the use of using primitive data type as opposed to their wrapper counter parts have any due effects on their serialization?

我有一个问题,使用原始数据类型而不是它们的包装计数器部分是否对其序列化有任何应有的影响?

For example, i have a class Person

例如,我有一个类 Person

public class Person implements Serializable{
private int age;
}

as opposed to

public class Person implements Serializable{
private Integer age;
}

What are their differences?

它们的区别是什么?

采纳答案by Buhake Sindi

I'm speaking in terms of Java's Serialization:

我说的是 Java 的序列化:

While intis a primitive type, which stores only the value of the variable (in binary), the Integerobject (using ObjectOutputStream) will store some "metadata" that when deserialization occurs, it will see the Integerobject.

虽然int是原始类型,它只存储变量的值(二进制),Integer对象(使用ObjectOutputStream)将存储一些“元数据”,当反序列化发生时,它会看到Integer对象。

Yes, serialization not only stores the object, but also the states of the object, so if you store,

是的,序列化不仅存储对象,还存储对象的状态,所以如果你存储,

private Integer value = 5;

The value is "wrapped" (lack of better word) inside Integerand the whole object is stored.

该值在内部“包装”(缺少更好的词)Integer并存储整个对象。

Added note: In order notto store an object/variable, mark the field with a transient, .e.g

补充说明:为了存储对象/变量,用transient, .eg标记该字段

transient private Integer value = 5;

Related Resources:

相关资源:

回答by Thilo

Well, the exact serialization format will be slightly different (just the 32 bits versus a serialized Integer object containing the 32 bits and a header), but both will be serialized and deserialized just fine.

好吧,确切的序列化格式将略有不同(仅 32 位与包含 32 位和标头的序列化 Integer 对象),但两者都将被序列化和反序列化就好了。

If declaring member data as primitive data types, will values be serialized if object is declared serializable?

如果将成员数据声明为原始数据类型,如果对象声明为可序列化,值是否会被序列化?

Yes, everything that is not marked transientwill be serialized, including primitives.

是的,未标记的所有内容都transient将被序列化,包括原语。

What are you trying to do?

你想做什么?