-1

I have an object with a HashMap field and a few methods that I am trying to serialize. However, at runtime, I am getting a java.io.NotSerializableException.

I was checking to see if HashMaps could be serialized and from what I have read they are so I am not sure what the problem is.

I was just wondering what makes an object be able to be serialized and why would this object that seems to only have fields that can be serialized not be able to as well.

azro
  • 53,056
  • 7
  • 34
  • 70
Guy Blum
  • 3
  • 2

1 Answers1

1

This is defined in the Java platform Spec here:

https://docs.oracle.com/javase/7/docs/platform/serialization/spec/serial-arch.html

The basic rules are these:

"A Serializable class must do the following:

  • Implement the java.io.Serializable interface

  • Identify the fields that should be serializable (Use the serialPersistentFields member to explicitly declare them serializable or use the transient keyword to denote nonserializable

  • Have access to the no-arg constructor of its first nonserializable superclass"

Broadly, in the absence of any indication to the contrary, and field that is not explicitly marked "transient" is a candidate for serialization.

The entire object graph from the target object downwards has to be serializable, or nothing is. That is, every field that references an object (not a primitive) must reference a serializable object.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15