views:

334

answers:

4

We can avoid serialising fields by using the transient keyword. Is there any other way of doing that?

+6  A: 

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.

T.J. Crowder
+12  A: 

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:

  1. Declare the field as private transient.
  2. Define the serialPersistentFields field of the class in question, and omit the field from the list of field descriptors.
  3. 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.

Serialization architecture specification.

Security in Object Serialization.

adatapost
can u please explain the 2nd method in detail..
cdb
Declaring serialPersistenetFields - This is done using a special static final variable called serialPersistentFields.
adatapost
+5  A: 

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

Paul Keeble
+2  A: 

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.

dfa