views:

87

answers:

4

I am just starting with JAVA serialization, I have one exercise to do and I need to lock serialization on any class, it is suppose to throw an exception when I attempt to serialize that class. Does anyone know how to do it? Thank you

+1  A: 

Serialization is available only for classes that implement Serializable (read the docs of this interface). I don't think you can switch it of at runtime. If you don't want objects to be serializable, don't make them implement Serializable.

If the serialization is within your control (i.e. you are calling ObjectOutputStream.writeObject(..)), then just make a configuration option that will disallow that call.

Another option would be to implement the writeObject(ObjectOutputStream out) method of and throw an exception depending on a configuration option.

Bozho
+3  A: 

If you add an implementation of writeObject which throws an exception, serialization will be aborted, e.g.

  private void writeObject(ObjectOutputStream stream) throws IOException {
    throw new RuntimeException("Don't want to serialize today");
  }

See http://java.sun.com/developer/technicalArticles/ALT/serialization/ for a good introduction to overriding the default serialization behaviour.

Simon Nickerson
I would recommend throwing a more specific `UnsupportedOperationException` instead of the general `RuntimeException`.
binil
+2  A: 

From http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void writeObject(java.io.ObjectOutputStream out) throws IOException<br/>
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

You could always try to overload the writeObject with the signature above, and throw the exception.

aioobe
Thank you for your answers, now I think I understand how does it work.
PaulP89
A: 

Thank you for all answers, now I think I understand it all.

PaulP89