Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB, and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, which means you can serialize an object in a platform and deserialize it on a different platform.
In Java, a NotSerializableException exception is thrown when an instance of a class must implement the Serializable interface. The exception is thrown by either the serialization runtime, or by the instance of the class. The argument for the NotSerializableException is the name of the class.
The NotSerializableException class extends the ObjectStreamException class, which is defined as the superclass of all exceptions specific to Object Stream classes. Also, the ObjectStreamException class extends the IOException which signals that an I/O exception has occurred.
Illustration:Â
java.io
Class NotSerializableException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.ObjectStreamException
java.io.NotSerializableException
Note: All Implemented Interfaces are Serializable interface.Â
Syntax:
public class NotSerializableException extends ObjectStreamException
Let us discuss the constructors of this class before a
- NotSerializableException(): Constructs a NotSerializableException object.
- NotSerializableException(String classname): Constructs a NotSerializableException object with message string.
Example 1:
Java
// Java Program to Illustrate NotSerializableException// Where Exception Is ThrownÂ
// Importing required classesimport java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;Â
// Class 1// Helper classclass Employee {Â
    // Member variables    private String id;Â
    // Member methodsÂ
    // Method 1    // To get ID of an employee    public String getId() { return id; }Â
    // Method 1    // To set ID of an employee    public void setId(String id)    {Â
        // this keyword refers to current object itself        this.id = id;    }}Â
// Class 2// Main Classpublic class GFG {Â
    // Main driver method    public static void main(String[] args)        throws IOException    {Â
        // Create FileOutputStream class object to        // create a file        FileOutputStream out            = new FileOutputStream("employee.dat");Â
        // Similarly creating ObjectOutputStream class        // object        ObjectOutputStream outputStream            = new ObjectOutputStream(out);Â
        // Creating objects of class 1        Employee obj = new Employee();Â
        // Assifning ID to an employee        obj.setId("001");Â
        // Writing objects to stream        outputStream.writeObject(obj);Â
        // Good practice is always to        // Close the stream using close() method        outputStream.close();    }} |
Â
Â
Output :Â
Errors in Code
Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "employee.dat" "write")
at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
at java.base/java.security.AccessController.checkPermission(AccessController.java:897)
at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)
at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:225)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:126)
at NotSerializableExceptionExample.main(NotSerializableExceptionExample.java:21)
How to deal with the NotSerializableException
- The simplest solution is to find the class that throws the exception and makes it implement the Serializable interface. However, this may not be feasible if the class that throws the exception belongs to a third-party library.
- In case the class refers to non-serializable objects and these objects should not be serialized, then, you can declare these objects as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.
Â
Example 2:
Java
// Java Program to Illustrate NotSerializableException// where No Exception is Thrown Using Serializable interfaceÂ
// Importing input output classimport java.io.Serializable;Â
// By implementing Serializable interface// we are allowing Student object to// be stored in TestFile.txtÂ
// Class 1// Helper class extending to Serializable interfaceclass Student implements Serializable {Â
    // Member variables of this class    int id;    String name;Â
    // Constructor of this class    public Student(int id, String name)    {        this.id = id;        this.name = name;    }}Â
// Class 2// Main classclass Persist {Â
    // Main driver method    public static void main(String args[])    {Â
        // try block to check for exceptions        try {Â
            // Creating the object            Student s1 = new Student(007, "Test");Â
            // Creating stream and writing the object            FileOutputStream fout                = new FileOutputStream("TestFile.txt");            ObjectOutputStream out                = new ObjectOutputStream(fout);Â
            out.writeObject(s1);            out.flush();Â
            // Closing the stream to free up memory space            // using close() method            out.close();Â
            // Display command to shown proper execution of            // a program            System.out.println(                "Object stored successfully");        }Â
        // Catch block to handle the exceptions        catch (Exception e) {Â
            // Print and display the exception on the            // console            System.out.println(e);        }    }} |
Â
Â
Output:
Object stored successfully
Â

