FindBugs - SE_BAD_FIELD, why does it ignore java.lang.Object?

From the description of SE_BAD_FIELD :

Continuous non-serializable instance field in serialized class

This Serializable class defines a non-primitive instance field that is not temporary, Serializable or java.lang.Object, and does not seem to implement the Externalizable interface or the readObject () and writeObject () methods. Objects of this class will not be deserialized correctly if an object without Serializable is stored in this field.

Why is java.lang.Object exception to the rule?

+6
source share
2 answers

The number of false positives will be potentially high, since

 public void writeIt(Object o, ObjectOutputStream oos) { oos.writeObject(o); } 

may be fine, as the caller always passes an instance of the derived class, which is Serializable.

Now the question is why the method signature is not specified

 public void writeIt(Serializable o, ObjectOutputStream oos) { oos.writeObject(o); } 

the answer is that then all kinds of objects defined by the interfaces passed as the first parameter are not compiled.

such as

 Map m = ..... writeIt(m, oos); 

therefore, the value of catching serializing java.lang.Object (which is probably an extremely rare event) is not worth the false positive impact.

+2
source

Since everything can be deserialized back to java.lang.Object, as each class in java extends java.lang.Object. If you manage to serialize an object that has a non-serializable field, you have no way to find out the class of this field during deserialization. Since each class is an object, you can always return to the Object class.

  class NonSerializableUser {} class SerializableUser implements Serializable{} class SomeObject implements Serializable{ public NonSerializableUser nonUser; public SerializableUser user; public Object nonUserObj; public SomeObject(SerializableUser u, NonSerializableUser uu, NonSerializableUser uuu){ user = u; nonUser = uu; nonUserObj = uuu; } } 

In this example, deserializing this class will cause nonUser to be empty, and the user to be the correct instance of the SerializableUser class, and nonUserObj to be non-null, but it will lose all methods and NonSerializableClass fields, they will not be serialized. The only parts of this instance that get serialized are the methods and fields that belong to the object.

It is worth noting that many serialization libraries (ObjectOutputStream, for example) will complain about a non-serializable class and will not serialize this object in the first place. This is why I forgot the details of the serialization / deserialization phase. However, many xml frameworks will still serialize these classes, and this is usually the situation where this error occurs in the head.

+1
source

Source: https://habr.com/ru/post/887377/


All Articles