20

I have a java class that implements serializable and I'm assuming the variable within the class would also be serialized but SonarQube is complaining to me that it is not.

My snippet of code is shown below:

SonarQube Error

koala421
  • 786
  • 3
  • 11
  • 27

3 Answers3

15

SonarQube marked this line as an error, because java.util.List doesn't implement java.io.Serializable. java.util.ArrayList is serializable, but the bondAxeMarkQuoteUpdates is protected so somebody can assign other non-serializable list to it (e.g. in a subclass).

To solve the problem you can:

  1. make the field as transient, but it will be ignored during serialization
  2. make the field as private, so SonarQube can verify that nobody assigned non-serializable list to it
  3. change the field type to serializable type (e.g. java.util.ArrayList)
agabrys
  • 8,728
  • 3
  • 35
  • 73
10

I receive the same error and the solution was turn the class used on the variable as Serializable.

For example, this show an error because Object is not Serializable:

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

The simplest solution in the case was turn the second parameter Serializable. So, you could use:

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

If you are using your own class (instead of Object), you can put the class to implements Serializable.

Dherik
  • 17,757
  • 11
  • 115
  • 164
  • This does not help in my case unfortunately( – ITisha Dec 20 '19 at 08:47
  • Serializable is a marker interface. What is the rationale of turning the second parameter as Serializable? – jumping_monkey Jan 10 '20 at 07:21
  • 1
    Serializable is not replacement of Object. – Atul Kumar May 29 '20 at 10:44
  • This is the proper approach, though some clarification is needed. A collection is considered serializable if all child classes are serializable. String is serializable, but Object is not necessarily, as all instances in Java ultimately extend Object, but not all object instances implement Serializable. By using Serializable instead, or by making a custom element class implement Serializable, the collection is enforced through type safety to only contain serializable children, and can therefore be trusted to be a serializable collection. – Stephan Oct 12 '20 at 19:56
-1

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

This rule raises an issue on non-Serializable fields, and on collection fields when they are not private (because they could be assigned non-Serializable values externally)

benzonico
  • 10,635
  • 5
  • 42
  • 50
  • 1
    I understand that but I'm confused as to how I can get for example `private Map map = new HashMap();` to have `Object` Serialized – koala421 May 12 '17 at 16:04
  • @koala421, see this answer: https://stackoverflow.com/a/48141335/2387977 – Dherik Jan 07 '18 at 20:43