开发者

How to lock serialization in Java?

I am just starting with Java serializati开发者_StackOverflow社区on: 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?


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.


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 }


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜