瞬态int的反序列化值?

时间:2011-08-03 05:57:33

标签: java serialization

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

假设我们正在序列化......

Employee e = new Employee();
e.name="REUBEN";
e.id=94731;

现在,如果我将其反序列化,那么

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

很明显,由于idtransient,因此未将其发送到输出流。

我的问题是,这个零是int的默认值吗? 我们没有保存状态,所以输出为0,但它也是一个值。不应该是null吗?

3 个答案:

答案 0 :(得分:9)

是的,类的成员变量在它们生成时(当它们在JVM中创建时)获得它们的默认值,因此为0,这是原始int类型的默认值。如果这导致“验证”ID是否被发送出现问题,只需使用Integer即可获得默认值null(并非它应该是任何混淆的来源,只是说)。

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

答案 1 :(得分:7)

它不能为null,因为int是基本类型。相反,它接收类型的默认值,即0。它始终是任何类型的“自然0” - 引用类型为null,数字类型为0,char为U + 0000和false boolean。有关详细信息,请参阅section 4.12.5 of the Java Language Specification

请注意,如果您只是声明一个实例/静态变量并在写入之前读取它,那么这也是您获得的默认值。

如果您想允许id为空,则需要将其设为Integer而不是int

答案 2 :(得分:0)

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