Tuesday, 6 October 2015

How to solve NotSerializableException?

Solve Not Serializable Exception


If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime.

The simplest way is to find the class that throws the exception and make it implement the Serializable interface. However, this may not be feasible if the class that throws the exception belongs to a third-party library i.e. org.apache.log4j.Logger.

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.

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

class Employee {
      private String id;

      public String getId() {
            return id;

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

/** java.io.NotSerializableException Example. */
public class NotSerializableExceptionExample {
      public static void main(String[] args) throws 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();

            //Write objects to stream

            //Always close the stream

Exception in thread "main" java.io.NotSerializableException: core.geeks.Employee at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330) at core.NotSerializableExceptionExample.main(NotSerializableExceptionExample.java:32)

Fix java.io.NotSerializableException in org.apache.log4j.Logger

org.apache.log4j.Logger  is simple, you have to prevent logger instance from default serializabtion process, either make it transient or static.

Making it transient after deserialization logger instance will be null and any logger.debug() call will result in NullPointerException.

By making it static and final you ensure that its thread-safe and all instance of Employee class can share same logger instance.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...