We are using HashMap
in JDK 1.7
and I face some issue during the code review with SonarQube.
Please consider below samples:
public class SerializationTest implements Serializable {
private Map<String,String> test1=new HashMap<>(); //Serializeable
private Map<ANEnum,String> test2=new HashMap<>(); //Serializeable
private Map<String,ASerializeableObject> test3=new HashMap<>(); //Serializeable
private Map<String,Map<String,String>> test4=new HashMap<>(); //Not Serializeable
private Map<ANEnum,Map<String,String>> test5=new HashMap<>(); //Not Serializeable
private Map<String,Map<String, ASerializeableObject>> test6=new HashMap<>(); //Not Serializeable
The Sonar mark last three HashMap
s as not serializeable
. The Sonar error is (Make "test4" transient or serializable
)
As far as I guessed the HashMap
is serializeable
if its key and value are serializeable
. But it seems that if I set a HashMap
value as another HashMap
, the original HashMap
will not be serializeable
at all.
Is this Sonar Issue correct ?! If it is how can I fix it ?!
Let's see each line, one by one:
The key type, String, is serializable. The value type, String, is serializable. The concrete Map type, HashMap, is serializable. So everything is serializable.
The key type, ANEnum, is serializable. The value type, String, is serializable. The concrete Map type, HashMap, is serializable. So everything is serializable.
The key type, String, is serializable. The value type, ASerializeableObject, is serializable. The concrete Map type, HashMap, is serializable. So everything is serializable.
The key type, String, is serializable. The concrete Map type, HashMap, is serializable. But the value type, Map, is not necessarily serializable. Some concrete implementations of Map (like HashMap), are serializable. Some others are not. So Sonar can't guarantee that this field is serializable, and issues a warning. If you're sure that you will only store serializable maps as values, no problem. If you store non-serializable maps, then the serialization will fail at runtime.
Same explanation as before
Same explanation as before
Remember that Sonar is only a tool, which can sometimes help, and sometimes get in the way. You should be in control, and decide if a warning should make you change things, or not.