We can avoid serialising fields by using the transient keyword.
Is there any other way of doing that?
Can we deny a java object from serialization other than giving transient keyword
15.5k views Asked by Biju CD AtThere are 4 answers
On
If for some reason transient doesn't suit, you can do the serialization directly by overriding the writeObject and readObject methods. Then you can include or omit any fields you need.
On
This is what transient means as a a keyword. Its whole purpose is to stop the serialization of the data for whatever reason.
If you wanted a finer grain control over the process you can use the writeObject/readObject methods that the ObjectOutputStream/ObjectInputStream use as part of the serialization process, and you could combine that with some custom annotations or any logic you wanted.
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException
On
You can create your own protocol with the Externalizable interface, that in my opinion is a nicer than Serializable since it doesn't contains private methods hooked by the JVM (writeObject and readObject). Instead of implementing the Serializable interface, you can implement Externalizable, which contains two methods:
public void writeExternal(ObjectOutput out) throws IOException;
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
Unlike using Serializable nothing is provided for free now, though. That is, the protocol is entirely in your hands, overring transient/non triansient fields, etc.
http://java.sun.com/javase/6/docs/platform/serialization/spec/security.html
Here are some links.
Declaring serialPersistenetFields.
Serialization architecture specification.
Security in Object Serialization.