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();
}

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.