简体   繁体   中英

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?

If you add an implementation of writeObject which throws an exception, serialization will be aborted, eg

  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.

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.

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 null s.

private static final ObjectStreamField[] serialPersistentFields = { null }

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM