Does enum’s field have to be Serializable?

I’m analyzing Java SE 7 project by SonarQube version 5.1.

Then, I faced squid:S1948 on below code.

Fields in a “Serializable” class should either be transient or serializable

Fields in a Serializable class must themselves be either Serializable or transient even if the class is never explicitly serialized or deserialized. That’s because under load, most J2EE application frameworks flush objects to disk, and an allegedly Serializable object with non-transient, non-serializable data members could cause program crashes, and open the door to attackers.

enum ShutterSpeed {
   private final Rational value; // Make "value" transient or serializable.

I think that any enum fields won’t be serialized in J2SE 5.0 (Serialization of Enum Constants)

Is this a false-positive?

Whole code and issue are here.


It is actually a false-positive. The Serialization of Enum Constants (which you’ve provided a link to) says that:

Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form.

As I see it, it doesn’t make sense to mark Enum‘s field values as transient or make them implement Serializable, since they’ll never get serialized, no matter if they’re marked as transient or implement Serializable.

If that analyzing tool forces you to do one of these two things, then you’ll be writing useless code. If I were you, I’d try to disable that warning for enums.

Leave a Reply

Your email address will not be published. Required fields are marked *