Friday, 9 October 2015

java.io.NotSerializableException

java.io.NotSerializableException is thrown when the object is not eligible for the serialization. We must implement the Serializable interface to make the class eligible for the serialization. This is a marker interface which tells the JVM that the class can be serialized.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

class Student {
      private String id;

      public String getId() {
            return id;
      }

      public void setId(String id) {
            this.id = id;
      }
}

public class NotSerializableExceptionTest {
      public static void main(String[] args) throws IOException{
            //Create FileOutputStream to create file
            FileOutputStream out = new FileOutputStream("student.dat");

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

            //Create objects
            Student obj = new Student();
            obj.setId("001");

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

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

Output:
      Exception in thread "main"java.io.NotSerializableException: Student
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at NotSerializableExceptionTest.main(NotSerializableExceptionTest.java:30)

How to fix java.io.NotSerializableException?

Student class must implement the serializable interface.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...