Is there a library that will recursively dump/print an objects properties? I\'m looking for something similar to the console.dir() function in Firebug.
I wanted an elegant solution to this problem that:
Does not use any external library
Uses Reflection to access fields, including superclass fields
Uses recursion to traverse the Object-graph with only one stack frame per call
Uses an IdentityHashMap to handle backwards references and avoid infinite recursion
Handles primitives, auto-boxing, CharSequences, enums, and nulls appropriately
Allows you to choose whether or not to parse static fields
Is simple enough to modify according to formatting preferences
I wrote the following utility class:
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.IdentityHashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
* Utility class to dump {@code Object}s to string using reflection and recursion.
*/
public class StringDump {
/**
* Uses reflection and recursion to dump the contents of the given object using a custom, JSON-like notation (but not JSON). Does not format static fields.
* @see #dump(Object, boolean, IdentityHashMap, int)
* @param object the {@code Object} to dump using reflection and recursion
* @return a custom-formatted string representing the internal values of the parsed object
*/
public static String dump(Object object) {
return dump(object, false, new IdentityHashMap
I tested it on a number of classes and for me it's extremely efficient. For example, try using it to dump the main thread:
public static void main(String[] args) throws Exception {
System.out.println(dump(Thread.currentThread()));
}
Edit
Since writing this post I had reason to create an iterative version of this algorithm. The recursive version is limited in depth by total stack frames, but you might have reason to dump an extremely large object graph. To handle my situation, I revised the algorithm to use a stack data structure in place of the runtime stack. This version is time-efficient and is limited by heap size instead of stack frame depth.
You can download and use the iterative version here.