tags:

views:

68

answers:

2

Hi, I have a class that implements java.io.Serializable interface.So all the variables in that class is serilaizable. But i want to make some of the variables are should not serializable. Is it possible?

thanks, Ravi

+4  A: 

Mark those variables as transient.

e.g.

class A implements Serializable{
    int a;
    transient int b;
}

When an object of A is serialized, the transient field b will not be serialized.

missingfaktor
Thanks Grey..But any other way?
Ravi K Chowdary
What's wrong with `transient`? How else would you want to do it?
skaffman
You can write your own custom readObject and writeObject and serialize what you like how you like. But one keyword is simpler.
Peter Lawrey
or maybe `java.io.Externalizable`?
missingfaktor
@peter: Great job..Thanks a lot
Ravi K Chowdary
Peter Lawrey: You should be always calling `defaultReadObject`, `defaultWriteObject`, `getFields` or `putFields` (might have got the names wrong - compiler will tell you) at the start of your `readObject`/`writeObject`. kalyaniRavi: There is another way involving a `static final` field name `serialPersistentFields` (something like that - if you misspell it, the compiler will not tell you!).
Tom Hawtin - tackline
+1  A: 

If you don't want to use transient (why not?), you can implement Externalizable and implement your own protocol:

public class Spaceship implements Externalizable {

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        // ...
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        // ...
    }

}

If that's too extreme, maybe you just want to customize the serialization a bit? Keep implementing Serializable and implement your own writeObject and readObject methods.

Here's a bunch of examples: http://java.sun.com/developer/technicalArticles/Programming/serialization/

ZoogieZork