PaulP89
PaulP89

Reputation: 31

How to lock serialization in Java?

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?

Upvotes: 3

Views: 1070

Answers (4)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

The three custom serialisation methods you want to provide are writeObject, readObject and readObjectNoData. The appropriate exception to throw is the appropriately named 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 little trick (though not actually specified in the spec) is to cause an NPE when the system attempts to create the matching java.io.ObjectStreamClass. I <3 nulls.

private static final ObjectStreamField[] serialPersistentFields = { null }

Upvotes: 3

aioobe
aioobe

Reputation: 420951

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 could always try to overload the writeObject with the signature above, and throw the exception.

Upvotes: 2

Bozho
Bozho

Reputation: 597046

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.

Upvotes: 1

Simon Nickerson
Simon Nickerson

Reputation: 43159

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.

Upvotes: 5

Related Questions