Reputation:
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.
Upvotes: 8
Views: 4715
Reputation: 71
Note that in addition to Task implementing Serializable, the outer class must also be Serializable. You may end up serializing unnecessary member states.
Upvotes: 7
Reputation: 533530
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)
Upvotes: 8
Reputation: 1101
Sure! In your case class Task should implement the Serializable interface.
Upvotes: 0
Reputation: 1851
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.
Upvotes: 0