Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Java objects into Java code

Tags:

java

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.

like image 215
user17456 Avatar asked Sep 18 '08 09:09

user17456


3 Answers

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.
like image 95
Tom Hawtin - tackline Avatar answered Oct 29 '22 16:10

Tom Hawtin - tackline


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

like image 22
Simon Collins Avatar answered Oct 29 '22 17:10

Simon Collins


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!

like image 1
paweloque Avatar answered Oct 29 '22 16:10

paweloque