Can we deny a java object from serialization other than giving transient keyword

后端 未结 4 980
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 05:53

We can avoid serialising fields by using the transient keyword. Is there any other way of doing that?

4条回答
  •  佛祖请我去吃肉
    2020-12-30 06:31

    You can create your own protocol with the Externalizable interface, that in my opinion is a nicer than Serializable since it doesn't contains private methods hooked by the JVM (writeObject and readObject). Instead of implementing the Serializable interface, you can implement Externalizable, which contains two methods:

    public void writeExternal(ObjectOutput out) throws IOException;
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    

    Unlike using Serializable nothing is provided for free now, though. That is, the protocol is entirely in your hands, overring transient/non triansient fields, etc.

提交回复
热议问题