Monday, 25 April 2016

When the NotSerializableException occurs ?


java.io.NotSerializableException is thrown when the object is not eligible for the serialization.

To fix this problem, implement the Serializable interface in the class.


Example
class Employee {
      private String empId;

      public String getEmpId() {
            return empId;
      }

      public void setEmpId(String empId) {
            this.empId = empId;
      }
}

/**
 Trying to serialize the non-Serializable object
 */
public class Test {
      public static void main(String[] argsthrows IOException {
          // Create FileOutputStream to create file
          FileOutputStream out = new FileOutputStream("employee.dat");

          // Create ObjectOutputStream
          ObjectOutputStream outputStream = new ObjectOutputStream(out);

          // Create objects
          Employee obj = new Employee();
          obj.setEmpId("143011");

          // Write objects to stream
          outputStream.writeObject(obj);

          // Close the stream
          outputStream.close();
      }
}


Output
      Exception in thread "main" java.io.NotSerializableException: Employee
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at Test.main(Test.java)


Solution
Just implement Serializable interface to the class which is being Serialized

class Employee implements Serializable {
   ...
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.