Why does SonarQube give a temporary / private error when the class is serialized?

I have a Java class that implements serializable, and I assume that the variable within the class will be serialized as well, but SonarQube complains to me that it is not.

My code snippet is shown below:

SonarQube Error

+6


source to share


3 answers


SonarQube marked this line as an error because java.util.List does not implement java.io.Serializable . java.util.ArrayList is serializable, but bondAxeMarkQuoteUpdates

protected

so someone might assign another non- serializable list to it (e.g. in a subclass).

To solve the problem, you can:



  1. make a field transient

    , but it will be ignored during serialization
  2. make a field private

    so SonarQube can make sure no one has assigned a non-serializable list to it
  3. change the field type to a serializable type (like java.util.ArrayList )
+9


source


I am getting the same error and the solution was to turn the class used in a variable like Serializable

.

For example, this shows an error because Object

not Serializable

:

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

      



The simplest solution in this case was to rotate the second parameter Serializable

. So you can use:

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

      

If you are using your own class (instead of Object

), you can put the class in implements Serializable

.

+8


source


As stated in the rules documentation (which you can open by clicking on ... in the screenshot): https://sonarqube.com/coding_rules#rule_key=squid%3AS1948

This rule causes a problem in non-serializable fields and in collection fields if they are not private (since they can be assigned outside Serializable values ​​externally)

-1


source







All Articles