Skip to content
Advertisement

Serialize Java objects into Java code

Does somebody know a Java library which serializes a Java object hierarchy into Java code which generates this object hierarchy? Like Object/XML serialization, only that the output format is not binary/XML but Java code.

Advertisement

Answer

I am not aware of any libraries that will do this out of the box but you should be able to take one of the many object to XML serialisation libraries and customise the backend code to generate Java. Would probably not be much code.

For example a quick google turned up XStream. I’ve never used it but is seems to support multiple backends other than XML – e.g. JSON. You can implement your own writer and just write out the Java code needed to recreate the hierarchy.

I’m sure you could do the same with other libraries, in particular if you can hook into a SAX event stream.

See: HierarchicalStreamWriter

Advertisement