Making Child classes as Non Serializable in java

前端 未结 7 1242
無奈伤痛
無奈伤痛 2020-12-09 16:43

I have a class which implements Serializable. Now I extends this class and I want this extended class to be non Serializable. So how to do it?

For example. I have

相关标签:
7条回答
  • 2020-12-09 17:22

    You can't remove the interface, but you can prevent serialization at run-time:

    class B extends A {
        private void writeObject(ObjectOutputStream oos) throws IOException {
            throw new NotSerializableException();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 17:23

    That's indeed not possible. Your best bet is to let B composite/decorate A.

    public class B {
        private A a = new A();
    
        public void doSomething() {
            a.doSomething();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 17:24

    Not possible. Liskov Substitution Principle and all.

    0 讨论(0)
  • 2020-12-09 17:25

    As others have made clear, it's not possible for a subclass of a Serializable class to be non-Serializable.

    If what you want is for the subclass' attributes not to be serialized, one option is to make them all transient.

    If you need more than that (you don't want super class fields to be serialized), override writeObject(ObjectOutputStream) and readObject(ObjectInputStream) as outlined here - https://web.archive.org/web/20120626144013/http://java.sun.com/developer/technicalArticles/ALT/serialization

    0 讨论(0)
  • 2020-12-09 17:34

    Answering one of your comment (and assuming you are talking of JPA or Hibernate):

    But Any class which wants its object to be persisted should implement this. and I want my Class B's objects as non persistable.

    If you don't want B to be persistent at all, don't mark it as @Entity. But it doesn't really make sense for B to extend A if B is not a persistent entity IMHO. This would be a bad use of inheritance.

    0 讨论(0)
  • 2020-12-09 17:35

    It will always be Serializable, though you could ensure nothing in the class ever gets serialized by making every member transient.

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