If member of class does not implement Serializable interface - than NotSerializableException is thrown in java.



If any of the member does not implement Serializable than  NotSerializableException is thrown.


We will use MyClass as a member variable of Serializable class.




Full Program/SourceCode to show that if any of the member does not implement Serializable than  NotSerializableException is thrown>

package SerDeser10memberNotSer;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
class MyClass {}

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

/*Author : AnkitMittal  Copyright- contents must not be reproduced in any form*/
class Employee implements Serializable {
  
   private static final long serialVersionUID = 1L;
   private Integer id;
   private MyClass myClass ;
  
   public Employee(Integer id) {
          this.id = id;
          myClass=new MyClass();
   }
   @Override
   public String toString() {
          return "Employee [id=" + id + "]";
   }
}
public class SerializeDeser {
   public static void main(String[] args) {
          Employee object1 = new Employee(8);
          try {
                 OutputStream fout = new FileOutputStream("ser.txt");
                 ObjectOutput oout = new ObjectOutputStream(fout);
                 System.out.println("Serialization process has started, serializing objects...");
                 oout.writeObject(object1);
                 System.out.println("Object Serialization completed.");
                 fout.close();
        oout.close();
         
          } catch (IOException  e) {
                 e.printStackTrace();
          }
   }
}
/*OUTPUT
Serialization process has started, serializing objects...
java.io.NotSerializableException: SerDeser10memberNotSer.MyClass
   at java.io.ObjectOutputStream.writeObject0(Unknown Source)
   at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
   at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
   at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
   at java.io.ObjectOutputStream.writeObject0(Unknown Source)
   at java.io.ObjectOutputStream.writeObject(Unknown Source)
   at SerDeser10memberNotSer.SerializeConstructorCheck.main(SerializeConstructorCheck.java:42)
*/
If we note output, myClass didn’t implemented Serializable interface that’s why Serialization process has thrown NotSerializableException.

How to avoid NotSerializableException?
We got to ensure that during Serialization all the members of class implements Serializable.




RELATED LINKS>

serialVersionUID  >

More about Serialization >





eEdit
Must read for you :