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