RKCY
RKCY

Reputation: 4135

serializable interface

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

Upvotes: 4

Views: 563

Answers (3)

Hitesh Garg
Hitesh Garg

Reputation: 1211

You can make the variable a transient one and can look the article below for completely understanding the Serializable Interface

http://www.codingeek.com/java/io/object-streams-serialization-deserialization-java-example-serializable-interface/

Upvotes: 0

ZoogieZork
ZoogieZork

Reputation: 11289

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/

Upvotes: 1

missingfaktor
missingfaktor

Reputation: 92106

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.

Upvotes: 4

Related Questions