Java – the difference between transient final and transient final wrapper types for basic types

What is the difference between transient final int and transient final integer

Use int:

transient final int a = 10;

Before serialization:

a = 10

After serialization:

a = 10

Use integer:

transient final Integer a = 10;

Before serialization:

a = 10

After serialization:

a = null

Full code:

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();
    }
}

}

Solution

As described in the article

http://www.xyzws.com/Javafaq/can-transient-variables-be-declared-as-final-or-static/0

Making a field transient prevents its serialization with one exception:

If you will access the JSL mentioned, you will know

However, integer is not the original type, it is not string, so it is not considered a candidate for constant expression, so its value will not be retained after serialization

demonstration:

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);
    }
}

Output:

10
null
foo
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>