Martijn Burger Martijn Burger - 4 months ago 15
Java Question

How to make a Generic Type Serializable?

SonarQube gives the following bug:

Make "type" transient or serializable.

On the following class:

public class InsuredAmount<T extends IAType> implements Serializable {

private static final long serialVersionUID = 1L;

private T type;

is an interface:

public interface IAType {


With various enum implementations, like:

public enum OneIAType implements IAType, Serializable {



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?

  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?