tags:

views:

451

answers:

4

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.

A: 

XStream is a serialization library I used for serialization to XML. It should be possible and rather easy to extend it so that it writes Java code.

Roman Plášil
+2  A: 

Serialised data represents the internal data of objects. There isn't enough information to work out what methods you would need to call on the objects to reproduce the internal state.

There are two obvious approaches:

  • Encode the serialised data in a literal String and deserialise that.
  • Use java.beans XML persistence, which should be easy enough to process with your favourite XML->Java source technique.
Tom Hawtin - tackline
The objects are java beans, so for all fields there are getters and setters. I don't care about deserialization, I just want to provide a way to help our developers with writing mocking code :)
+1  A: 

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

Simon Collins
Or apply a XSL transformation to whatever XStream outputs and so generate java. whichever you're appeals more to you.
entzik
A: 

Great question. I was thinking about serializing objects into java code to make testing easier. The use case would be to load some data into a db, then generate the code creating an object and later use this code in test methods to initialize data without the need to access the DB.

It is somehow true that the object state doesn't contain enough info to know how it's been created and transformed, however, for simple java beans there is no reason why this shouldn't be possible.

Do you feel like writing a small library for this purpose? I'll start coding soon!

lewap