Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

transient and Externalizable

 
Sharda Vajjhala
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always thought transient members were not serializable i.e. couldn't be written out. But as the example below illustrates, if it's an Externalizable object, then transient members are also written out.
import java.io.*;
public class TransientWriter implements Externalizable
{

private transient String s = "Hope I can ever be persistant!";
public TransientWriter(){
System.out.println("TransientWriter Constructor");
}
public void writeExternal(ObjectOutput oOut) throws IOException
{
oOut.writeObject(s);
}

public void readExternal(ObjectInput oIn) throws IOException,
ClassNotFoundException
{
s=(String)oIn.readObject();
}
public String toString()
{
return s;
}
}
class K
{
public static void main(String args[]) throws IOException,
ClassNotFoundException
{
TransientWriter tw = new TransientWriter();
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("tw.out"));
out.writeObject(tw);
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("tw.out"));
TransientWriter tw2 = (TransientWriter) in.readObject();
System.out.println(tw2);
}
}
This actually writes out the string value of s in the file. And prints to the screen:
TransientWriter Constructor
TransientWriter Constructor
Hope I can ever be persistant!

Thanks
Sharda
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By implementing Externalizable, you have complete control over the serialization process, that is, you can serialize whatever fields you want to. Transient fields are not serialized by the default serialization process (when implementing Serializable).
For more detailed information, please consult Java tutorial: Implementing the Externalizable Interface
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic