Yes, you can print it recursively by overriding toString
in all your classes.
If you want to have a method like printObjectRecursively(Object o)
you need to dive into reflection, fetch the fields, print their name and content recursively using printObjectRecursively(someField)
.
Example:
public class Test {
public static void main(String[] args) {
A a = new A();
System.out.println(a);
}
}
class A {
int i = 5;
B obj = new B();
String str = "hello";
public String toString() {
return String.format("A: [i: %d, obj: %s, str: %s]", i, obj, str);
}
}
class B {
int j = 17;
public String toString() {
return String.format("B: [j: %d]", j);
}
}
Prints:
A: [i: 5, obj: B: [j: 17], str: hello]
A reflection-based recursive print method could be written something like this
private static final List LEAVES = Arrays.asList(
Boolean.class, Character.class, Byte.class, Short.class,
Integer.class, Long.class, Float.class, Double.class, Void.class,
String.class);
public static String toStringRecursive(Object o) throws Exception {
if (o == null)
return "null";
if (LEAVES.contains(o.getClass()))
return o.toString();
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getSimpleName()).append(": [");
for (Field f : o.getClass().getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers()))
continue;
f.setAccessible(true);
sb.append(f.getName()).append(": ");
sb.append(toStringRecursive(f.get(o))).append(" ");
}
sb.append("]");
return sb.toString();
}