Search code examples
javaserializabletransient

Use transient keyword in not Serializable class


Would it make sense to use the transient keyword in a class that does not implement Serializable?

Because classes that do not implement Serializable could still be serialized by the ObjectOutputStream.


Solution

  • Because classes that do not implement Serializable could still be serialized by the ObjectOutputStream.

    That is incorrect. That would throw a NotSerializableException.


    The reason writeObject() takes an Object instead of Serializable is that the signature comes from implementing the interface ObjectOutput which is defined independent of serialization. But, it then prevents ObjectOutputStream from changing its signature.

    public interface ObjectOutput {
      // ...
      void writeObject(Object obj);
    }