Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is SonarQube giving a transient/private error when class is Serialized?

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

like image 807
koala421 Avatar asked May 11 '17 14:05

koala421


People also ask

What happens if your serializable class contains a member which is not serializable how do you fix it?

It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field.

How do you make a list transient or serializable?

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 .

How do you serialize a transient variable 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.

What is transient and serializable in Java?

transient is a Java keyword which marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes.


1 Answers

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)
like image 196
agabrys Avatar answered Sep 18 '22 12:09

agabrys