Reputation: 9
The usecase is the following, I have a generic class as follows:
public class Test<T> implements Serializable {
private T testObject;
.....
}
With sonarLint off course complaining about the field testObject should be made either transient or serializable.
If I would make the required/proposed change as follows:
public class Test<T extends Serializable> implements Serializable {
private T testObject;
.....
}
Although if I want to make use of this Generic Test class, then I can't use it together with interface types like for example a List interface, because a List is of course not Serializable.
This doesn't compile, but is in my opinion the preferred way programming to the interface.
public Test<List<String>> doSomething() {
}
This compiles, but is actually not what I want...
public Test<ArrayList<String>> doSomething() {
}
So, not sure what the answer to my question is.... should I ignore the SonarLint warning or is there a different way to solve/bypass this?
Upvotes: 1
Views: 122
Reputation: 181159
An object that holds a reference to a non-Serializable object cannot be serialized via the default serialization algorithm. For your particular case, there is no type-safe way to engage custom serialization. You therefore have only three main options:
Do not modify your original code, and accept that it lies when it declares itself Serializable
. If it actually matters to you that the class be Serializable
-- that is, you plan to serialize instances -- then this creates a non-negligible failure risk, but you could get away with it if, in practice, the testObject
member always is serializable. This is effectively the strategy employed by java.util.ArrayList
and some other serializable standard library classes.
Do not make your class Serializable
. Then the immediate problem goes away, but of course, instances are even more not default-serializable. That may not work for you.
Implement the proposed change you describe, with T extends Serializable
(or extends
some other serializable type). This is the type-safe alternative. It avoids risk of serialization failure insomuch as that is within your class's control. The cost is as you describe -- the type parameter will exclude types that are not serializable. For the specific case of List
s, you could instead use one of the serializable List
implementations in place of the List
interface, but you'll have to determine how well that works for you, technically and stylistically.
We can't tell you which of those is best for your particular purposes. You'll have to decide that for yourself.
Upvotes: 3