Dumping a java object's properties

后端 未结 10 1685
-上瘾入骨i
-上瘾入骨i 2020-11-28 02:03

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.

I\'m aware o

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 02:25

    You can use ReflectionToStringBuilder with a custom ToStringStyle, for example:

    class MyStyle extends ToStringStyle {
        private final static ToStringStyle instance = new MyStyle();
    
        public MyStyle() {
            setArrayContentDetail(true);
            setUseShortClassName(true);
            setUseClassName(false);
            setUseIdentityHashCode(false);
            setFieldSeparator(", " + SystemUtils.LINE_SEPARATOR + "  ");
        }
    
        public static ToStringStyle getInstance() {
            return instance;
        };
    
        @Override
        public void appendDetail(StringBuffer buffer, String fieldName, Object value) {
            if (!value.getClass().getName().startsWith("java")) {
                buffer.append(ReflectionToStringBuilder.toString(value, instance));
            } else {
                super.appendDetail(buffer, fieldName, value);
            }
        }
    
        @Override
        public void appendDetail(StringBuffer buffer, String fieldName, Collection value) {
            appendDetail(buffer, fieldName, value.toArray());
        }
    }
    

    And then you invoke it like:

    ReflectionToStringBuilder.toString(value, MyStyle.getInstance());
    

    Beware of circular references though!


    You can also use json-lib (http://json-lib.sourceforge.net) and just do:

    JSONObject.fromObject(value);
    

提交回复
热议问题