NotSerializableException in Java with Examples
Last Updated :
05 Jan, 2022
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 classes
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
// Class 1
// Helper class
class 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 Class
public 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 class
import 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 interface
class 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 class
class 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
Similar Reads
NumberFormatException in Java with Examples
The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. Â That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java. I
3 min read
OverlappingFileLockException in Java with Examples
An OverlappingFileLockException is thrown when attempting to acquire a lock that overlaps an existing or pending lock held by this process. This exception is thrown by the lock( ) and tryLock( ) methods of FileChannel if the requested lock region overlaps a file lock that is already held by some thr
5 min read
Vector setSize() method in Java with Example
The Java.util.Vector.setSize() is a method of Vector class that is used to set the new size of the vector. If the new size of the vector is greater than the current size then null elements are added to the vector is new size is less than the current size then all higher-order elements are deleted. T
3 min read
Vector trimToSize() method in Java with Example
The trimToSize() method of Vector in Java trims the capacity of an Vector instance to be the Vector's current size. This method is used to trim an Vector instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not retur
2 min read
java.io.UnsupportedEncodingException in Java with Examples
The java.io.UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String get
3 min read
Throwable toString() method in Java with Examples
The toString() method of Java.lang.Throwable class used to return a String representation of this Throwable which consists of the name of the class of this object, a colon and a space(": ") and a string which is same as result of invoking this object's getLocalizedMessage() method and If getLocalize
2 min read
Serialization and Deserialization in Java with Example
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent. So,
6 min read
Throwable Class in Java with Examples
Classes and Objects are basic concepts of Object-Oriented Programming which revolve around real-life entities. A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In this article,
7 min read
Java PatternSyntaxException Class getIndex() Method with Examples
Java PatternSyntaxException Class is defined under the java.util.regex package and it depicts unchecked exception that signifies syntax error in a regular expression pattern. This class can be declared using the below syntax, public class PatternSyntaxException extends IllegalArgumentExceptionPatter
2 min read
ToDoubleFunction Interface in Java with Examples
The ToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an argument of type T and produces a double-valued result. This functional interface takes in only o
1 min read