Serialization in java -NotSerializableException

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 Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

WHEN CAN IT OCCUR

1. When you serialize an inner class instance

java.io.NotSerializableException can occur when you serialize an inner class instance because:

2. When attempting to serialize or deserialize an object that does not implement the java.io.Serializable interface

Below is the full code sample:

package io.airbrake;

import io.airbrake.utility.Logging;

import java.io.*;
import java.util.GregorianCalendar;

public class Main {

public static void main(String[] args) {
// Create book and test serialization.
Book nameOfTheWind = new Book("The Name of the Wind", "Patrick Rothfuss", 662, new GregorianCalendar(2007, 2, 27).getTime());
testBookSerialization(nameOfTheWind);

// Create and test another book.
Book wiseMansFear = new Book("The Wise Man's Fear", "Patrick Rothfuss", 994, new GregorianCalendar(2011, 2, 1).getTime());
testBookSerialization(wiseMansFear);
}

/**
* Tests serialization of passed Book object.
*
* @param book Book to be tested.
*/
private static void testBookSerialization(Book book) {
// Determine serialization file name.
String fileName = String.format("%s.ser", book.toFilename());
// Output file info.
Logging.lineSeparator(String.format("SAVING TO FILE: %s", fileName), 75);
// Serialize Book to file.
serialize(book, fileName);
// Deserialize Book from file.
deserialize(fileName);
}

/**
* Serializes the passed object to the passed filePath.
*
* @param object Object that is being serialized.
* @param filePath File path where object should be stored.
*/
private static void serialize(Object object, String filePath) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
fileOutputStream.close();
Logging.log(String.format("SERIALIZED [%s]: %s", object.getClass().getName(), object));
} catch (NotSerializableException exception) {
// Output expected NotSerializeableExceptions.
Logging.log(exception);
} catch (IOException exception) {
// Output unexpected IOException.
Logging.log(exception, false);
}
}

/**
* Deserializes object found in passed filePath.
*
* @param filePath Path to file where serialized object is found.
* @param <T> Type of object that is expected.
*/
private static <T> void deserialize(String filePath) {
try {
FileInputStream fileInputStream = new FileInputStream(filePath);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
T object = (T) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
Logging.log(String.format("DESERIALIZED [%s]: %s", object.getClass().getName(), object));
} catch (NotSerializableException exception) {
// Output expected NotSerializeableExceptions.
Logging.log(exception);
} catch (IOException | ClassNotFoundException exception) {
// Output unexpected IOExceptions and ClassNotFoundExceptions.
Logging.log(exception, false);
}
}
}
// Book.java
package io.airbrake;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.*;
import io.airbrake.utility.Logging;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.util.Date;

/**
* Simple example class to store book instances.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Book implements Serializable
{
private String author;
private String title;
private Integer pageCount;
private Date publishedAt;
private static String publicationType = "Book";

private static final Integer maximumPageCount = 4000;

/**
* Ensure publication type is upper case.
*/
static {
publicationType = publicationType.toUpperCase();
}

/**
* Constructs an empty book.
*/
public Book() { }

/**
* Constructs a basic book.
*
* @param title Book title.
* @param author Book author.
*/
public Book(String title, String author) {
setAuthor(author);
setTitle(title);
}

/**
* Constructs a basic book, with page count.
*
* @param title Book title.
* @param author Book author.
* @param pageCount Book page count.
*/
public Book(String title, String author, Integer pageCount) {
setAuthor(author);
setPageCount(pageCount);
setTitle(title);
}

/**
* Constructs a basic book, with page count.
*
* @param title Book title.
* @param author Book author.
* @param pageCount Book page count.
*/
public Book(String title, String author, Integer pageCount, Date publishedAt) {
setAuthor(author);
setPageCount(pageCount);
setTitle(title);
setPublishedAt(publishedAt);
}

/**
* Constructs a basic book, with page count.
*
* @param title Book title.
* @param author Book author.
* @param pageCount Book page count.
*/
public Book(String title, String author, Integer pageCount, Date publishedAt, String publicationType) {
setAuthor(author);
setPageCount(pageCount);
setTitle(title);
setPublishedAt(publishedAt);
setPublicationType(publicationType);
}

/**
* Get author of book.
*
* @return Author name.
*/
public String getAuthor() {
return author;
}

/**
* Get page count of book.
*
* @return Page count.
*/
public Integer getPageCount() {
return pageCount;
}

/**
* Get publication type of book.
*
* @return Publication type.
*/
public String getPublicationType() { return publicationType; }

/**
* Get published date of book.
*
* @return Published date.
*/
public Date getPublishedAt() { return publishedAt; }

/**
* Get a formatted tagline with author, title, page count, and publication date.
*
* @return Formatted tagline.
*/
public String getTagline() {
return String.format("'%s' by %s is %d pages, published %s.",
getTitle(),
getAuthor(),
getPageCount(),
DateFormat.getDateInstance().format(getPublishedAt()));
}

/**
* Get title of book.
*
* @return Title.
*/
public String getTitle() {
return title;
}

/**
* Publish current book.
* If book already published, throws IllegalStateException.
*/
public void publish() throws IllegalStateException {
Date publishedAt = getPublishedAt();
if (publishedAt == null) {
setPublishedAt(new Date());
Logging.log(String.format("Published '%s' by %s.", getTitle(), getAuthor()));
} else {
throw new IllegalStateException(
String.format("Cannot publish '%s' by %s (already published on %s).",
getTitle(),
getAuthor(),
publishedAt));
}
}

/**
* Set author of book.
*
* @param author Author name.
*/
public void setAuthor(String author) {
this.author = author;
}

/**
* Set page count of book.
*
* @param pageCount Page count.
*/
public void setPageCount(Integer pageCount) throws IllegalArgumentException {
if (pageCount > maximumPageCount) {
throw new IllegalArgumentException(String.format("Page count value [%d] exceeds maximum limit [%d].", pageCount, maximumPageCount));
}
this.pageCount = pageCount;
}

/**
* Set publication type of book.
*
* @param type Publication type.
*/
public void setPublicationType(String type) { this.publicationType = type; }

/**
* Set published date of book.
*
* @param publishedAt Page count.
*/
public void setPublishedAt(Date publishedAt) {
this.publishedAt = publishedAt;
}

/**
* Set title of book.
*
* @param title Title.
*/
public void setTitle(String title) {
this.title = title;
}

/**
* Get the filename formatted version of this Book.
*
* @return Filename.
*/
String toFilename() {
try {
return java.net.URLEncoder.encode(String.format("%s-%s", getTitle(), getAuthor()).toLowerCase(), "UTF-8");
} catch (UnsupportedEncodingException exception) {
Logging.log(exception);
}
return null;
}

/**
* Output to JSON string.
*
* @return
* @throws JsonProcessingException
*/
public String toJsonString() throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(this);
}

/**
* Get string representation of Book.
*
* @return String representation.
*/
public String toString() {
return getTagline();
}

/**
* Throw an Exception.
*/
public void throwException(String message) throws Exception {
throw new Exception(message);
}
}
/**
* Tests serialization of passed Book object.
*
* @param book Book to be tested.
*/
private static void testBookSerialization(Book book) {
// Determine serialization file name.
String fileName = String.format("%s.ser", book.toFilename());
// Output file info.
Logging.lineSeparator(String.format("SAVING TO FILE: %s", fileName), 75);
// Serialize Book to file.
serialize(book, fileName);
// Deserialize Book from file.
deserialize(fileName);
}
public static void main(String[] args) {
// Create book and test serialization.
Book nameOfTheWind = new Book("The Name of the Wind", "Patrick Rothfuss", 662, new GregorianCalendar(2007, 2, 27).getTime());
testBookSerialization(nameOfTheWind);
// Create and test another book.
Book wiseMansFear = new Book("The Wise Man's Fear", "Patrick Rothfuss", 994, new GregorianCalendar(2011, 2, 1).getTime());
testBookSerialization(wiseMansFear);
}
-------- SAVING TO FILE: the+name+of+the+wind-patrick+rothfuss.ser --------
SERIALIZED [io.airbrake.Book]: 'The Name of the Wind' by Patrick Rothfuss is 662 pages, published Mar 27, 2007.
DESERIALIZED [io.airbrake.Book]: 'The Name of the Wind' by Patrick Rothfuss is 662 pages, published Mar 27, 2007.
------- SAVING TO FILE: the+wise+man%27s+fear-patrick+rothfuss.ser --------
SERIALIZED [io.airbrake.Book]: 'The Wise Man's Fear' by Patrick Rothfuss is 994 pages, published Mar 1, 2011.
DESERIALIZED [io.airbrake.Book]: 'The Wise Man's Fear' by Patrick Rothfuss is 994 pages, published Mar 1, 2011.
�� sr io.airbrake.Bookm���smh4 L authort Ljava/lang/String;L  pageCountt Ljava/lang/Integer;L publishedAtt Ljava/util/Date;L titleq ~ xpt Patrick Rothfusssr java.lang.Integer⠤���8 I valuexr java.lang.Number������  xp  �sr java.util.Datehj�KYt  xpw  �1��xt The Name of the Wind
public class Book
{
// ...
}
-------- SAVING TO FILE: the+name+of+the+wind-patrick+rothfuss.ser --------
[EXPECTED] java.io.NotSerializableException: io.airbrake.Book
[UNEXPECTED] java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: io.airbrake.Book
------- SAVING TO FILE: the+wise+man%27s+fear-patrick+rothfuss.ser --------
[EXPECTED] java.io.NotSerializableException: io.airbrake.Book
[UNEXPECTED] java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: io.airbrake.Book

3. If the superclass is serializable but we don’t want the subclass to be serialized.

It can be achieved by implementing the writeObject() and readObject() methods in the subclass and throwing NotSerializableException from these methods.

i = 10
j = 20
Exception in thread "main" java.io.NotSerializableException
at B.writeObject(Test.java:44)

4. When superclass implements marker interface

The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata. In java, it is used as interfaces with no method specified.

Developer, melomaniac, philospher, tea lover