开发者

Making an Exception field transient in Java

I have a class that extends Exception, and therefore has to be Serializable. The exception class contains a field that is not Serializable, so I was considering making it Transient. My understanding is that doing so, will mean that the field cannot be recovered if my class is stored. When d开发者_如何学运维uring execution might my Exceptions be serialized/deserialized? (n.b. As far as I know, I'm not writing these to a database or file).


If you are not explicitly serialising them yourself, then I think its safe to assume that making your field transient will have no bad effects.

From my understanding, the JVM does not serialise objects without being explicitly asked to do so, so, unless expect the Exception class to be serialised by your application, I don't think you have cause to worry.

I guess that if you are writing a library, and therefore can't know all the use cases of your class, you may need to be a little more careful.


If the exception is being propagated through RMI, RPC frameworks or similar then it may cause trouble. If you do not use such functionalities, then you can make it transient.


Your understanding is correct. Fields marked as transient are not considered as part of an object's state and are intentionally left out when the object is serialized, and won't be recovered when the object is deserialized again. Serialization happens when you want to store an object and its state on disk or send an object over the network. As far as I know, serialization doesn't happen during normal program execution, unless you tell your program explicitly to do so..


You could define writeObject to throw UnsupportedOperationException or NotSerializableException to ensure this object is never Serialised.


Yes, if you have transient fields in your exception, the transient fields cannot be restored if your object gets serialized/deserialized.

However, in small applications it is unlikely, that you need serialization/deserialization if you do not serialize the exceptions by yourself. But pay attention if you use any "magic" framework or JNDI or any clustered environment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜