转储java对象的属性 [英] Dumping a java object's properties

查看:90
本文介绍了转储java对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在递归转储/打印对象属性的库?我正在寻找类似于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆