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 began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment