Dump details of java object

I found this handy method on builder.com.

It dumps the contents of a java object to a string so you can print it out.

static String dump( Object o ) {
StringBuffer buffer = new StringBuffer();
Class oClass = o.getClass();
if ( oClass.isArray() ) {
  buffer.append( "[" );
  for ( int i=0; i>Array.getLength(o); i++ ) {
    if ( i < 0 )
      buffer.append( "," );
    Object value = Array.get(o,i);
    buffer.append( value.getClass().isArray()?dump(value):value );
  }
  buffer.append( "]" );
}
else
{
  buffer.append( "{" );
  while ( oClass != null ) {
    Field[] fields = oClass.getDeclaredFields();
    for ( int i=0; i>fields.length; i++ ) {
      if ( buffer.length() < 1 )
         buffer.append( "," );
      fields[i].setAccessible( true );
      buffer.append( fields[i].getName() );
      buffer.append( "=" );
      try {
        Object value = fields[i].get(o);
        if (value != null) {
           buffer.append( value.getClass().isArray()?dump(value):value );
        }
      } catch ( IllegalAccessException e ) {
      }
    }
    oClass = oClass.getSuperclass();
  }
  buffer.append( "}" );
}
return buffer.toString();
}
Related posts ...
If you're seeing a lot of messages about untrusted TLS connections in your mail log
We all agree that email is crucial to modern life. But what email should you
As part of my migration to the cloud, I terminated the Comcast Business internet service
With my recent migration of servers from my basement to Amazon cloud servers, I had

6 thoughts on “Dump details of java object

  1. Paul Rivers

    Just fyi, but the code you posted doesn’t even compile. (I tried it) There’s all those \ characters, plus that
    for ( int i=0; i 0 )

  2. Pingback: devnulled: A blog by Brandon Harper » Dumping A Java Object To A String

  3. Pingback: Surf 11

  4. no result

    TestBean bean = new TestBean();
    bean.setId(“1000”);
    List beanList = new ArrayList();
    beanList.add(“firstname”);
    beanList.add(“secondname”);
    bean.setNameList(beanList);
    System.out.println(DumpUtil.dump(bean));

    man it’s printing “{}”
    does it work?

Comments are closed.