skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Tuesday, October 16, 2012

Transient variable Demo using File Operations

Posted by Raju Gupta at 12:00 PM – 0 comments
 

If a field of an object is transient, when that object is persisted (saved), the value of the transient field will not be persisted.

The TransientDemo class demonstrates this. It contains an inner class, MyDemo, which has a String field named "x" and a transient String field named "y". In the main() method, TransientDemo instatiates a MyDemo object with x set to "normal" and y set to "transient". This object is saved to the file system as a file called "mydemo.ser". We then read this persisted object and get a reference to it called "result". When we display the values of x and y after we've retrieved the object, we can see that the value of x is there but the value of y is null, since it wasn't persisted.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/*This is a demo to show transient variable can't be saved using File serialization. */
public class TransientDemo {

 public static void main(String[] args) {

  class MyDemo implements Serializable {
   private static final long serialVersionUID = 1L;
   String x;
   transient String y;

   MyDemo(String x, String y) {
    this.x = x;
    this.y = y;
   }

   public String toString() {
    return "x is " + x + ", y is " + y;
   }
  }

  try {
   MyDemo md = new MyDemo("normal", "transient");
   System.out.println("Before save: " + md);

   // write object to file
   FileOutputStream fos = new FileOutputStream("mydemo.ser");
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   oos.writeObject(md);
   oos.close();

   // read object from file
   FileInputStream fis = new FileInputStream("mydemo.ser");
   ObjectInputStream ois = new ObjectInputStream(fis);
   MyDemo result = (MyDemo) ois.readObject();
   ois.close();

   System.out.println("After save: " + result);

  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }

}


Labels: Java File Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger