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;
2

There are 2 best solutions below

6
On BEST ANSWER

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.

2
On

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.