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

前端 未结 9 994
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:27

    What data may cause the NotSerializableException?

    In Java, we serialize object (the instance of a Java class which has already implemented the Serializable interface). So it's very clear that if a class has not implemented the Serializable interface, it cannot be serialized (then in that case NotSerializableException will be thrown).

    The Serializable interface is merely a marker-interface, in a way we can say that it is just a stamp on a class and that just says to JVM that the class can be Serialized.

    How should I know that I am not supposed to add the implements Serializable clause for my class?

    It all depends on your need.

    1. If you want to store the Object in a database, you can serialize it to a sequence of byte and can store it in the database as persistent data.

    2. You can serialize your Object to be used by other JVM working on different machine.

    0 讨论(0)
  • 2020-12-25 12:30

    NotSerialisable exception is thrown when something in your serializable marked as serializable. One such case can be:

    class Super{}
    class Sub implements Serializable
    {
    Super super;
    

    Here super is not mentioned as serializable so will throw NotSerializableException.

    0 讨论(0)
  • 2020-12-25 12:31

    When you are talking about NotSerializableException it is throw when you want to serialize an object, which has not been marked as Serializable - that's all, although when you extend non serializable class, and add Serializable interface it is perfectly fine.

    There is no data that can't be serialized.

    0 讨论(0)
提交回复
热议问题