问题
Is it possible to searialize/desearialize anonymous class in Java?
Example:
ByteArrayOutputStream operationByteArrayStream = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(operationByteArrayStream);
oos.writeObject(new Task() {
public void execute() {
System.out.println("Do some custom task"));
}
});
My problem is that I want to do some custom admin tasks so that i don't need a release for every task. So what i'm trying to do - is via Groovy scripting engine post custom task via HTTP endpoint and serialize them into db to run them in time.
回答1:
It is possible, by dangerous. The name/number of anonymous classes is generated by the compiler and is based on the order they appear in the file. e.g. if you swap the order of two classes, their names will swap as well. (Classes are deserialized by name)
回答2:
Note that in addition to Task implementing Serializable, the outer class must also be Serializable. You may end up serializing unnecessary member states.
回答3:
This is certainly possible. Java generates an internal name for anonymous classes (Similar to DeclaredInThisClass$1, DeclaredInThisClass$2 if you declare them in a class called DeclaredInThisClass) and will happily serialize/deserialize them.
回答4:
Sure! In your case class Task should implement the Serializable interface.
来源:https://stackoverflow.com/questions/9465641/serialization-of-anonymous-class-in-java