javaeclipseobject-to-string

String representation of a large object model in Java?


I have a large object model which I'd like to print into a custom format textfile (could be up to 100000 rows). The model consists of a main class, which knows all its subelements (30 different classes). So, I'd need to print all the subelements and their attributes.

I have thought and tried using toString. Implementing it in such a way that calling toString from the main class would call all the subelements' toString methods as well, recursively. The main problem is that all of the data goes into one string, and as mentioned, there could be up to 100000 rows of text, so this doesn't sound too good. I need to create/generate (using Eclipse) toString methods for every class as well.

Another thought was to use an interface, which would be recursive in the same way, and I could then use it to print row at a time. The thing is, I need to write this implementation by hand for every class, in contrast to generating toStrings with Eclipse.

I'd appreciate ideas for this kind of scenario. Key points are easiness to implement (and read) plus streamish style of writing.

EDIT: I am implementing a standard (which originates from the 90's :), so that is why the output will be in "plain text", rather than formatted XML or even JSON.


Solution

  • OK, the another sought is better for a very simple reason. String stores data into a byte array. You said that you are going to create 100K lines of text. If each line contains 100 characters it is 10M bytes. I guess that such implementation will be very ineffective.

    So, define interface that accepts Object (unless you have interface or base class shared for all your classes) and OutputStream (or probably PrintStream), i.e.:

    interface ObjectPrinter {
        print(Object root, PrintStream out);
    }
    

    Now as @BorisTheSpider suggested iterate over graph of class members using reflection. If you do not know what reflection is take a look on java reflection API. The advantage of using stream is that you can print value chunk when you have it. You do not have to accumulate whole object graph before printing it as in case of putting all into String.

    Be aware that it is not an half an hour project. You have to care about all primitive types, arrays, collections, back references and loops, nulls etc. As a reference you can use ToStringBuilder or EqualsBuilder from Apache commons.