In this question says that final
transient
fields can not be set to any non-default value after serialization. So why I have 3 for aVar1
variable and s3 for aVar3
variable?
import java.io.*;
import java.util.*;
class Test
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
A a1 = new A();
// save a1 to file
FileOutputStream fileOutput = new FileOutputStream("a.dat");
ObjectOutputStream outputStream = new ObjectOutputStream(fileOutput);
outputStream.writeObject(a1);
fileOutput.close();
outputStream.close();
// load a1 from file
FileInputStream fiStream = new FileInputStream("a.dat");
ObjectInputStream objectStream = new ObjectInputStream(fiStream);
a1 = (A) objectStream.readObject();
fiStream.close();
objectStream.close();
// fields after deserialization
System.out.println(a1.aVar1); // 3
System.out.println(a1.aVar2); // null
System.out.println(a1.aVar3); // s3
System.out.println(a1.aVar4); // null
}
}
class A implements Serializable
{
public final transient int aVar1 = 3;
public final transient Map <Object, Object> aVar2 = new HashMap <> ();
public final transient String aVar3 = "s3";
public final transient String aVar4 = new String("s4");
}