Serializing an Anonymous Class in Java

Is it possible to absorb / desearialize an 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 perform some custom administration tasks, so I donโ€™t need a version for each task. So what I'm trying to do is, through Groovy, configure a custom script task using an HTTP endpoint and serialize them in db to run them on time.

+7
source share
4 answers

Perhaps dangerous. The name / number of anonymous classes is generated by the compiler and is based on the order that they display in the file. for example, if you change the order of two classes, their names will also change. (Classes are deserialized by name)

+6
source

Note that in addition to the task that implements Serializable, the outer class must also be Serializable. You can complete the serialization of unnecessary member states.

+6
source

It is certainly possible. Java generates an internal name for anonymous classes (similar to DeclaredInThisClass $ 1, DeclaredInThisClass $ 2 if you declare them in the DeclaredInThisClass class) and will happily serialize / deserialize them.

0
source

Of course! In your case, the Task class should implement the Serializable interface.

0
source

All Articles