转储Java对象的属性 [英] Dumping a java object's properties
问题描述
是否有一个可以递归转储/打印对象属性的库?我正在寻找类似于Firebug中的 console.dir()函数的东西.
Is there a library that will recursively dump/print an objects properties? I'm looking for something similar to the console.dir() function in Firebug.
我知道commons-lang ReflectionToStringBuilder ,但不会递归到对象中.即,如果我运行以下命令:
I'm aware of the commons-lang ReflectionToStringBuilder but it does not recurse into an object. I.e., if I run the following:
public class ToString {
public static void main(String [] args) {
System.out.println(ReflectionToStringBuilder.toString(new Outer(), ToStringStyle.MULTI_LINE_STYLE));
}
private static class Outer {
private int intValue = 5;
private Inner innerValue = new Inner();
}
private static class Inner {
private String stringValue = "foo";
}
}
我收到:
ToString $ Outer @ 1b67f74 [ intValue = 5
innerValue = ToString $ Inner @ 530daa ]
ToString$Outer@1b67f74[ intValue=5
innerValue=ToString$Inner@530daa ]
我意识到在我的示例中,我可以为Inner覆盖toString()方法,但在现实世界中,我正在处理无法修改的外部对象.
I realize that in my example, I could have overriden the toString() method for Inner but in the real world, I'm dealing with external objects that I can't modify.
推荐答案
您可以尝试 XStream .
XStream xstream = new XStream(new Sun14ReflectionProvider(
new FieldDictionary(new ImmutableFieldKeySorter())),
new DomDriver("utf-8"));
System.out.println(xstream.toXML(new Outer()));
打印出:
<foo.ToString_-Outer>
<intValue>5</intValue>
<innerValue>
<stringValue>foo</stringValue>
</innerValue>
</foo.ToString_-Outer>
您还可以在 JSON
注意循环引用;)
这篇关于转储Java对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!