Martijn Burger Martijn Burger - 3 months ago 11
Java Question

How to make a Generic Type Serializable?

SonarQube gives the following bug:


Make "type" transient or serializable.


On the following class:

@XmlRootElement
public class InsuredAmount<T extends IAType> implements Serializable {

private static final long serialVersionUID = 1L;

private T type;
}


IAType
is an interface:

public interface IAType {

}


With various enum implementations, like:

public enum OneIAType implements IAType, Serializable {

GENERIC

}


The class is used in a REST interface, so it should be Serializable.

My Questions:
1. I don't think marking the type as transient is a good idea, because I am transferring this class via a REST interface. Can it lead to a problem if I mark this type as transient?
2. How can I make the type serializable?

Answer
  1. Can it lead to a problem if I mark this type as transient?

Depends if you need the value in the field after you deserialize the instance. If you do, you can mark it transient, but you need some other way to transfer the necessary information to reconstruct the value of type at the far end.

  1. How can I make the type serializable?

Declare the type variable as an intersection type:

<T extends IAType & Serializable>

Edit: it appears that this suggestion isn't recognised by SonarQube as a serializable type.

It says in the question that the implementations of the interface are enums; that suggests that an alternative way to express the bound would be:

<T extends Enum<T> & IAType>

Note that all enums are implicitly serializable, so Serializable doesn't have to be in the intersection type explicitly.

It turns out that this works; I am not entirely sure why, though! Perhaps it is a bug in SonarQube?