• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

transient and Externalizable

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic