问题
Why does ObjectOutputStream.writeObject(Object o) not take a Serializable? Why is it taking an Object
?
回答1:
This is because writeObject
in ObjectOutputStream
overrides the method in the ObjectOutput interface which does not require that the object be Serializable
.
The ObjectOutput
interface specifies methods that allow objects to be written to a stream or underlying storage, but this may be achieved by a process other than serialization. The ObjectOutputStream
implements this functionality, but requires serializable objects. However, it cannot modify the signature of the interface that it implements.
回答2:
It should be ObjectOutputStream.writeObject(serializable)
rather than ObjectOutputStream. writeObject(Object)
. It is a proper use case where a marker interface like Serializable
should have been used but unfortunately not. This would have made it possible the very real benefit of compile-time type checking instead of failing at runtime if the object does not implement Serializable
interface.
I would like to take this opportunity to mention what Joshua Bloch has mentioned in his book Effective java:
A marker interface is an interface that contains no method declarations, but merely designates (or “marks”) a class that implements the interface as having some property. For example, consider the Serializable interface. By implementing this interface, a class indicates that its instances can be written to an
ObjectOutputStream
(or “serialized”).In the case of the
Serializable
marker interface, theObjectOutputStream.write(Object)
method will fail if its argument does not implement the interface. Inexplicably, the authors of theObjectOutputStream
API did not take advantage of theSerializable
interface in declaring the write method. The method’s argument type should have beenSerializable
rather thanObject
. As it stands, an attempt to callObjectOutputStream.write
on an object that doesn’t implementSerializable
will fail only at runtime, but it didn’t have to be that way.
来源:https://stackoverflow.com/questions/5621690/why-does-objectoutputstream-writeobject-not-take-a-serializable