Java dump an object

2019-08-14 14:25发布

问题:

I need to dump all the attributes of a Java object. I have found a few functions that do this but none of them handle self references and all of the functions I have found spiral into infinite recursion.

//I will be running this function on Android but that shouldn't really matter.

回答1:

If this is just for debugging or if you want some form of basic serialization take a peek at XStream . Here is an example from their site talking about self references in particular...

Cd bj = new Cd("basement_jaxx_singles");

List order = new ArrayList();
// adds the same cd twice (two references to the same object)
order.add(bj);
order.add(bj);

// adds itself (cycle)
order.add(order);

XStream xstream = new XStream();
xstream.alias("cd", Cd.class);
System.out.println(xstream.toXML(order));

And the output is...

<list>
  <cd>
    <id>maria rita</id>
  </cd>
  <cd>
    <id>basement_jaxx_singles</id>
  </cd>
  <cd reference="../cd[2]"/>
  <list reference=".."/>
</list>