-1

In our application, for one class(which is Serializable) sonar is complaining - Fields in a "Serializable" class should either be transient or serializable. That class is not serialized anywhere in our application. But I am not sure why it implements serializable because that class was written long time ago.

As per the Sonar doc , Fields in a Serializable class must themselves be either Serializable or transient even if the class is never explicitly serialized or deserialized. But I didnt find any exact reason behind this.

Could you please explain why its harmful if Fields in a "Serializable" class is not transient or serializable ? if the class is never explicitly serialized or deserialized then what is the harm here ?

I was going through Fields in a “Serializable” class should either be transient or serializable, but I didnt find proper answer of my question. I found below statement but didnt understand much

For instance, 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. In general a Serializable class is expected to fulfil its contract and not have an unexpected behaviour when an instance is serialized.

Thanks

Rahman
  • 3,755
  • 3
  • 26
  • 43
  • the class being serialized or not is of no concern. If it is declared `Serializable`, it can, in future, be serialized. The compiler has no way to see in the future and know what will happen with the compiled class. If you don't need it to be serialized, do not implement the `Serializable` interface – user85421 Oct 04 '19 at 15:52
  • 1
    it's common for some people to make domain objects serializable even if they don't need to be. if you are certain it doesn't need to be serialized then remove the "implements Serializable". do these things get stuffed in an httpsession or passed around across the network? or put in a queue? – Nathan Hughes Oct 04 '19 at 15:54
  • @NathanHughes Yes . We put it in a queue – Rahman Oct 04 '19 at 15:56
  • @NathanHughes So you meant to say when application putting this class to a queue, implicitly object of that class is getting serialized ? – Rahman Oct 04 '19 at 15:59
  • 1
    Would have to see code to know for sure but seems very likely. – Nathan Hughes Oct 04 '19 at 16:31

1 Answers1

0

Serialization, transform an object to a stream of bytes. The object has to be serializable, and all its fields serializables because the serialization process serializes the object with all its fields, but if one field should/could not be serializable, it has to be explicitely marked as transient so it will be ignored. If its not ignored (marked as transient) an exception of type NotSerializableException will be thrown at serialization. If your class objects will not be serialized at some point, there is no need to implemet Serializable.

Sofiane Daoud
  • 868
  • 9
  • 21