How do I block serialization in Java?

I'm just getting started with Java serialization: I have one exercise and I need to block serialization in any class, so if I try to serialize that class, you should throw an exception.

Does anyone know how to do this?

+2


a source to share


4 answers


If you add an implementation writeObject

that throws an exception, serialization will abort, eg.

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

      



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

+5


a source


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
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

      

You can always try to overload with the writeObject

signature above and throw an exception.

+2


a source


The three custom serialization methods you want to provide are writeObject

, readObject

and readObjectNoData

. The corresponding exception for throw is the corresponding name java.io.NotSerializableException

.

private void writeObject(
    ObjectOutputStream out {
) throws IOException {
    throw new NotSerializableException();
}
private void readObject(
    ObjectInputStream in
) throws IOException, ClassNotFoundException {
    throw new NotSerializableException();
}
private void readObjectNoData( 
) throws ObjectStreamException {
    throw new NotSerializableException();
}

      

A small trick (although not actually specified in the spec) calls the NPE when the system tries to create a matching one java.io.ObjectStreamClass

. i <3 null

s.

private static final ObjectStreamField[] serialPersistentFields = { null }

      

+2


a source


Serialization is only available for classes that implement Serializable

(read the docs of this interface). I don't think you can switch it at runtime. If you don't want objects to be serializable, don't make them an implementation Serializable

.

If the serialization is within your control (i.e., you are calling ObjectOutputStream.writeObject(..)

), just put in a config parameter that will disallow this call.

Another option would be to implement the method writeObject(ObjectOutputStream out)

and throw an exception depending on the config setting.

+1


a source







All Articles