Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a Java object to Java code?

Is there an implementation that will serialize a Java object as Java code? For example, if I have the object

Map<String,Integer> m = new Map<String,Integer>();
m.put("foo",new Integer(21));

I could serialize this using

ObjectOutputStream out = new ObjectOutputStream( ... );
out.writeObject( m );
out.flush();

and the output would, for example, be

java.util.Map<String,Integer> m = new java.util.Map<String,Integer>(); 
m.put("foo",new Integer(21));

Why would you want this? Sometimes it is easier to partially create complex objects programmatically and then complete the creation manually in code. This code can then be included in the source and version controlled with everything else. Note that using external serialized objects is not exceptable.

Thanks for any help you can give.

like image 399
Andrew Gilmartin Avatar asked Jun 08 '11 15:06

Andrew Gilmartin


People also ask

How do you create a serialization in Java?

To make a Java object serializable we implement the java. io. Serializable interface. The ObjectOutputStream class contains writeObject() method for serializing an Object.

Why do we serialize objects in Java?

Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.

Can we serialize method in Java?

Since Method does not implement Serializable, it cannot be serialized using the standard Java Serialization API. A workaround would be to manually serialize just the name of the class and method and its parameter types. You can then recreate the Method instance during deserialization.


1 Answers

I implemented this functionality in a new github project. You can find the project here:

https://github.com/ManuelB/java-bean-to-code-serializer

The project does not have any external dependencies except junit.

Currently it is not supporting arrays for serialization yet. Nevertheless there is already a lot of functionalities:

        Object2CodeObjectOutputStream object2CodeObjectOutputStream = new Object2CodeObjectOutputStream(
            byteArrayOutputStream);
        object2CodeObjectOutputStream.writeObject(<your-java-bean>);
        System.out.println(
                byteArrayOutputStream.toString());
like image 192
Manuel_B Avatar answered Sep 29 '22 13:09

Manuel_B