Created
May 10, 2011 03:58
-
-
Save axiak/963879 to your computer and use it in GitHub Desktop.
Dumper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Array; | |
import java.lang.reflect.Field; | |
import java.math.BigDecimal; | |
import java.util.Arrays; | |
import java.util.List; | |
public class Dumper { | |
private static final Class[] printtableClasses = new Class[]{ | |
String.class, Integer.class, Float.class, Double.class, | |
BigDecimal.class, Character.class, Byte.class, | |
List.class | |
}; | |
private static boolean isPrintable(Object o) { | |
for (Class cls : printtableClasses) { | |
if (cls.isInstance(o)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
public static String dump( Object o ) { | |
StringBuffer buffer = new StringBuffer(); | |
Class oClass = o.getClass(); | |
System.out.println(oClass); | |
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(isPrintable(value) ? value.toString() : dump(value)); | |
} | |
buffer.append( "]" ); | |
} else { | |
buffer.append( "{" ); | |
while ( oClass != null ) { | |
Field[] fields = oClass.getDeclaredFields(); | |
System.out.println(Arrays.toString(fields)); | |
for ( int i=0; i < fields.length; i++ ) { | |
if ( buffer.length() > 2 ) | |
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(isPrintable(value) ? value.toString() : dump(value)); | |
} | |
} catch ( IllegalAccessException e ) { | |
throw new RuntimeException(e); | |
} | |
} | |
oClass = oClass.getSuperclass(); | |
} | |
buffer.append( "}" ); | |
} | |
return buffer.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment