Serializable and transient

后端 未结 5 1776
無奈伤痛
無奈伤痛 2021-01-02 06:24

To make a class serializable we do the following:

class A implements Serializable {
    transient Object a;
}

And not this:



        
5条回答
  •  时光取名叫无心
    2021-01-02 07:19

    Why isn't used some special keyword to mark classes as serializable too? Serializable interface looks like a magic numbers in code and not like the language feature.

    I think you have to look at it the other way: language keywords exist mainly to support compile-time language constructs. Serialization is a runtime mechanism. Additionally, you don't want to have an extra keyword for everything, because you then can't use it as an identifier. A marker interface on the other hand is much less intrusive.

    The question is thus: why do we need a language keyword to mark transient fields? And the answer is that there simply was no other way to mark specific fields at that time.

    Nowadays, one would use annotations for this purpose in both cases (and for other things like the obscure strictfp keyword as well).

提交回复
热议问题