Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization of anonymous class in Java

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.

like image 419
breedish Avatar asked Feb 27 '12 13:02

breedish


People also ask

What is an anonymous class in Java?

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.

Can we extend anonymous class in Java?

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.

Which class is used for serialization in Java?

The ObjectOutputStream class contains writeObject() method for serializing an Object.

Can private variables be serialized in Java?

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.


2 Answers

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)

like image 167
Peter Lawrey Avatar answered Sep 24 '22 05:09

Peter Lawrey


Note that in addition to Task implementing Serializable, the outer class must also be Serializable. You may end up serializing unnecessary member states.

like image 39
user1619637 Avatar answered Sep 22 '22 05:09

user1619637