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 Responses to “Dump details of java object”

  1. Paul Rivers Says:


    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. Davd Gibbs Says:


    I fixed up the formatting of the code so it’s compilable.
  3. devnulled: A blog by Brandon Harper » Dumping A Java Object To A String Says:


    [...] I came across what looks to be a handy method to dump a Java object to a string (and no, I don’t mean toString()). I guess I’m spoiled by <cfdump> in ColdFusion and have got used having a visual indicator as to what an object actually looks like when trying to debug something. I haven’t yet given this code a try so I can’t speak for how well it works, but I should have a use for it soon. Filed under: ColdFusion, Java « Black Rebel Motorcycle Club New Single — Ain’t No Easy Way   [...]
  4. Surf 11 Says:


    Display Java Object as a String
  5. no result Says:


    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?

  6. Dan Says:


    The for loop should be looping while i is less than fields.length

    for ( int i=0; i

Close
E-mail It