Java why a Map of Map (ex: Map>) not seria

2019-07-14 04:12发布

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 HashMaps 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 ?!

1条回答
放我归山
2楼-- · 2019-07-14 04:39

Let's see each line, one by one:

private Map<String,String> test1=new HashMap<>();

The key type, String, is serializable. The value type, String, is serializable. The concrete Map type, HashMap, is serializable. So everything is serializable.

private Map<ANEnum,String> test2=new HashMap<>(); 

The key type, ANEnum, is serializable. The value type, String, is serializable. The concrete Map type, HashMap, is serializable. So everything is serializable.

private Map<String,ASerializeableObject> test3=new HashMap<>();

The key type, String, is serializable. The value type, ASerializeableObject, is serializable. The concrete Map type, HashMap, is serializable. So everything is serializable.

private Map<String,Map<String,String>> test4=new HashMap<>();

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.

private Map<ANEnum,Map<String,String>> test5=new HashMap<>(); //Not Serializeable

Same explanation as before

private Map<String,Map<String, ASerializeableObject>> test6=new HashMap<>();

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.

查看更多
登录 后发表回答