Transient used to mark a variable not to be serialized
So if you are serializing an object and you don't want to serialize a partecular variable value inside it,
Then you just make it as transient and it will not be serialized
Below example explains this concept
*/
package javabeat.samples;
| import java.io.FileInputStream; |
| import java.io.FileOutputStream; |
| import java.io.IOException; |
| import java.io.ObjectInputStream; |
| import java.io.ObjectOutputStream; |
| import java.io.Serializable; |
| class NameStore implements Serializable{ |
| private String firstName; |
| private transient String middleName; |
| public NameStore (String fName, |
| public String toString(){ |
| StringBuffer sb = new StringBuffer( 40 ); |
| sb.append( "First Name : " ); |
| sb.append( this .firstName); |
| sb.append( "Middle Name : " ); |
| sb.append( this .middleName); |
| sb.append( "Last Name : " ); |
| sb.append( this .lastName); |
| public class TransientExample{ |
| public static void main(String args[]) throws Exception { |
| NameStore nameStore = new NameStore( "Steve" , |
| ObjectOutputStream o = new ObjectOutputStream |
| ( new FileOutputStream( "nameStore" )); |
| o.writeObject(nameStore); |
| ObjectInputStream in = new ObjectInputStream( |
| new FileInputStream( "nameStore" )); |
| NameStore nameStore1 = (NameStore)in.readObject(); |
| System.out.println(nameStore1); |
Comments
Post a Comment