开发者

Deserialized value of transient int?

public class Employee implements java.io.Serializable
{
 public String name;
 public int transient id;
}

Suppose we are serializing ...

Employee e = new Employee();
e.name="REUBEN";
e.id=9473开发者_如何转开发1;

Now if I deserialize this then

System.out.println("Name: " + e.name); will give the o/p REUBEN
System.out.println("ID: " + e.id); will give the o/p 0

It is clear that as id is transient it was not sent to the output stream.

My question is, this zero is the default value of int ?

We are not saving the state so it is giving the output as 0 , but it is also a value. Shouldn't it be null ?


Yes, member variables of a class get their default values when they come into being (when they are created in a a JVM) hence the 0, which is the default value of the primitive int type. If this is causing problems with "verifying" whether the ID was sent across or not, just use Integer which would get the default value of null (not that it should be a source of any confusion, just saying).

public class Employee implements java.io.Serializable
{
 public String name;
 public transient Integer id;
}
System.out.println("Name: " + e.name); will give the o/p REUBEN
System.out.println("ID: " + e.id); will give the o/p null


It can't be null, because int is a primitive type. Instead, it receives the default value for the type, which is 0. It's always the "natural 0" of any type - null for a reference type, 0 for numeric types, U+0000 for char, and false for boolean. See section 4.12.5 of the Java Language Specification for more details.

Note that this is also the default value you get if you just declare an instance/static variable and read it before writing to it.

If you want to allow id to be null, you need to make it an Integer rather than an int.


class Employee implements Serializable {

    private static final long serialVersionUID = 2915285065334004197L;
    transient int a; //Transient Variables are not serialized and returns 0/null after deserialization
    static int b; //Static Variable are not serialized and returns the current/updated value
    int c; //instance variables will be serialized

    public Employee() {

        this.a = 10;
        this.b = 20;
        this.c = 30;
    }
}

After seraialization O/P will be 0 20 30
Now, if you write below code after serialization and before deserialization as below
Employee e = new Employee();
e.a = 5;
e.b = 6;
e.c = 7;
O/P will be 0 6 30
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜