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();
}
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 )
…
I fixed up the formatting of the code so it’s compilable.
Pingback: devnulled: A blog by Brandon Harper » Dumping A Java Object To A String
Pingback: Surf 11
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?
The for loop should be looping while i is less than fields.length
for ( int i=0; i