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:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment