Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes transient and Externalizable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "transient and Externalizable" Watch "transient and Externalizable" New topic
Author

transient and Externalizable

Sharda Vajjhala
Ranch Hand

Joined: Nov 14, 2001
Posts: 57
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

Joined: Aug 26, 2001
Posts: 7610
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


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: transient and Externalizable
 
Similar Threads
TransientWriter
transient Variable
transient I.0
ob. serialization
transient