Why does ObjectOutputStream.writeObject not take a Serializable?

試著忘記壹切 提交于 2019-11-30 12:47:03

问题


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, the ObjectOutputStream.write(Object) method will fail if its argument does not implement the interface. Inexplicably, the authors of the ObjectOutputStream API did not take advantage of the Serializable interface in declaring the write method. The method’s argument type should have been Serializable rather than Object. As it stands, an attempt to call ObjectOutputStream.write on an object that doesn’t implement Serializable 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!