Great Deals

Serialization

19:07 suresh chaudhari 0 Comments

1.If class B is implementing serializable and it holds reference of class A which is not serialized then NonSerializable exception will be thrown at runtime.
>
Class A{}
 Class A implements Serializable
 {
  B b;
 }
2.When Object is deserialized it does not invoke the constructor. Reson is when we deserialize the Object we need to know it actual state but if constructor is called it will be changed to the default state objects. suppose
 class A
 {
 int a;
  A(int a)
  {
   this.a=a=3;//if constructor called in deserialization then value will be 3 which is inappropriate
  }
  changeA()
  {
  this.a=5;//here value is changed to 5
  }
}
4.Static variable will neve be part of serialization. 5.How to serialize the singleton variables
@Configurable
public class NotSingleton implements Serializable {
    @Autowired
    private transient SingletonClass singleton;
    
}
5. When the serializable class extends non serializable class then the instance variable of the parent class can get the state which is the state which is initialized by serialized child class.
import java.io.File;
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;

class NonSerial
{
int a=8;
NonSerial()
{
 System.out.println("called"+this.a);
}
}
class B extends NonSerial implements Serializable
{

 /**
  * 
  */
 
 
 private static final long serialVersionUID = 1L;
 B()
 {
  
 
 System.out.println("B  "+this.a);
  
 }
 public void getB()
 {
  this.a=12;
  
 }
}
public class SerializeDemo {

 public static void main(String[] args) {
  B bObj=new B();
  bObj.getB();
  try {
   ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(new File("a.txt")));
   os.writeObject(bObj);
   os.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 ObjectInputStream io = null;
 try {
  io = new ObjectInputStream(new FileInputStream(new File("a.txt")));
 } catch (FileNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 } catch (IOException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 }
 try {
  B b=(B) io.readObject();
  io.close();
  System.out.println("Later On "+b.a);
 } catch (ClassNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 }
}

0 comments:

Advertising