Java: What can and what can't be serialized?

前端 未结 9 1006
Happy的楠姐
Happy的楠姐 2020-12-25 11:48

If the Serializable interface is just a Marker-Interface that is used for passing some-sort of meta-data about classes in java - I\'m a bit confused:

After reading t

9条回答
  •  青春惊慌失措
    2020-12-25 12:18

    All the primitive data types and the classes extend either Serializable directly,

    class MyClass extends Serializable{
    }
    

    or indirectly,

    class MyClass extends SomeClass{
    }
    

    SomeClass implements Serializable.

    can be serialized. All the fields in a serializable class gets serialized except the fields which are marked transient. If a serializable class contains a field which is not serializable(not primitive and do not extend from serializable interface) then NotSerializableException will be thrown.

    Answer to the second question : As @JB Nizet said. If you are going to write the instance of a class to some stream then and then only mark it as Serializable, otherwise never mark a class Serializable.

提交回复
热议问题