How to fix java.io.NotSerializableException Error
- Details
- Written by Nam Ha Minh
- Last Updated on 28 October 2023   |   Print Email
In this post, I’d like to share a solution to fix the NotSerializableExceptionerror in Java. You know, when developing and running Java applications, you may get the following error:
java.io.NotSerializableException: <fully qualified class name>
For example (citing the top most of exception stack trace):
java.io.NotSerializableException: com.weatherapi.entity.User at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1197) ~[na:na] at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1582) ~[na:na] at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1539) ~[na:na] at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1448) ~[na:na] ...
The NotSerializableException error occurs because when the application tried to serialize a Java object, it found that the object’s class does not implement the Serializable interface, which is required by serialization process. For example:
public class User { ... }
The solution is make the class implements the java.io.Serializable interface and declares a field serialVersionUID, as shown below:
public class User implements Serializable { public static final long serialVersionUID = 1234L; ... }
And don’t worry about the value of the field serialVersionUID as you can specify any long value. That’s a simple way to fix the java.io.NotSerializableException error in Java.
Watch the following video to see how I fixed this error in a real life project:
To understand about background of serialization in Java, I recommend you check the following articles:
Other Java File IO Tutorials:
- How to Read and Write Text File in Java
- How to Read and Write Binary Files in Java
- Java IO - Common File and Directory Operations Examples
- Java Serialization Basic Example
- Understanding Java Externalization with Examples
- How to execute Operating System Commands in Java
- 3 ways for reading user's input from console in Java
- File change notification example with Watch Service API
- Java Scanner Tutorial and Code Examples
- How to compress files in ZIP format in Java
- How to extract ZIP file in Java
Comments