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.
To make a Java object serializable we implement the java. io. Serializable interface. The ObjectOutputStream class contains writeObject() method for serializing an Object.
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.
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.
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());
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