«

»

Dec 13 2004

Print this Post

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

4 comments

2 pings

Skip to comment form

  1. Dan

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

    for ( int i=0; i

  2. 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?

  3. Davd Gibbs

    I fixed up the formatting of the code so it’s compilable.

  4. 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 )


  1. Surf 11

    Display Java Object as a String

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

    […] 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   […]

Comments have been disabled.

css.php