Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar "Make transient or serializable" error

I have the following serializable class (implements serializable):

public class Test implements Serializable{

private String id;

private Map<String,Object> otherProperties;

}

However , it seems like this property is causing some problems with serialization :

enter image description here

How can I solve this problem ?

Also , is there any downside in not making this transient or serializable ? Will I be able to serialize this class fully ?

like image 964
Nexussim Lements Avatar asked Dec 09 '19 16:12

Nexussim Lements


People also ask

Can Transient be serialized?

In case you define any data member as transient, it will not be serialized. This is because every field marked as transient will not be serialized. You can use this transient keyword to indicate the Java virtual machine (JVM) that the transient variable is not part of the persistent state of an object.

How do you make a field serializable?

By making a field Public It is one of the simplest ways by which we can make a field serialize and de-serialize. In this way, we simply make the field public for this. We will declare a class with a public, a protected and a private field. By default, only the available field will be serialized to JSON.

What is transient and serializable in Java?

transient is a variables modifier used in serialization. At the time of serialization, if we don't want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type.

Is serializable consider declaring a serialVersionUID?

A serializable class can declare its own serialVersionUID explicitly by declaring a field named “ serialVersionUID ” that must be static, final, and of type long.


1 Answers

The Map interface does not extend the Serializable interface, which is why Sonar is warning you.

When serializing an instance of Test, you must choose whether or not you want otherProperties to be serialized.

If you don't want to serialize otherProperties, then the field should be marked as transient:

private transient Map<String, Object> otherProperties;

Otherwise, you can change the type of otherProperties to an implementation of Map that implements Serializable, such as HashMap.

like image 168
Jacob G. Avatar answered Sep 28 '22 21:09

Jacob G.