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.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.
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)
Note that in addition to Task implementing Serializable, the outer class must also be Serializable. You may end up serializing unnecessary member states.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With