We can avoid serialising fields by using the transient
keyword.
Is there any other way of doing that?
views:
334answers:
4If 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.
http://java.sun.com/javase/6/docs/platform/serialization/spec/security.html
SUMMARY:Preventing Serialization of Sensitive Data Fields containing sensitive data should not be serialized; doing so exposes their values to any party with access to the serialization stream. There are several methods for preventing a field from being serialized:
- Declare the field as private transient.
- Define the serialPersistentFields field of the class in question, and omit the field from the list of field descriptors.
- Write a class-specific serialization method (i.e., writeObject or writeExternal) which does not write the field to the serialization stream (i.e., by not calling ObjectOutputStream.defaultWriteObject).
Here are some links.
Declaring serialPersistenetFields.
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
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.