Is it possible to serialize transient field of the class using my custom serialization or using Externalization?

StackOverflow https://stackoverflow.com/questions/18605799

Question

Is it possible to serialize transient field of the class using my custom serialization or using Externalization?

Example: there is a class Person having name field transient

transient String name;

Is it possible to serialize it using below methods?

private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
Was it helpful?

Solution

The answer is yes if you are using the custom serializaton. When we do custom serialization by overriding the writeObject method, you take control of the serialization and can do whatever you want. So you can also assign or use a value of a transient field and can also marshall it along with other class attributes.

OTHER TIPS

You can write / read any fields including transient in writeObject / readObject. However it does not make much sense to first hide a field with transient then simply write / read it with custom serialization. Usually transient fields are not serialized at all or need some special processing with custom serialization.

As for Externalization it ignores transient, all fields are written / read explicitly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top