开发者

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

开发者 https://www.devze.com 2023-03-13 01:19 出处:网络
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?

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

public class Person implements Serializable{
private int age;
}

as opposed to

public class Person implements Serializable{
private Integer age;
}

What are their differences?


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

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

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 Integer and the whole object is stored.

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

transient private Integer value = 5;

Related Resources:

  • Discover the secrets of the Java Serialization API


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.

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

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

What are you trying to do?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号