Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively print an objects details

Tags:

java

recursion

How do I print the content of an object recursively?

like image 601
tom Avatar asked Oct 11 '10 10:10

tom


People also ask

What are recursive objects?

Objects can have other objects as attribute values. When an object of some class has an attribute value of that same class, it is a recursive object.

What is recursive function example?

A classic example of recursion The classic example of recursive programming involves computing factorials. The factorial of a number is computed as that number times all of the numbers below it up to and including 1. For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .

What does recursively mean in Java?

In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.


3 Answers

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();
}
like image 184
aioobe Avatar answered Sep 20 '22 06:09

aioobe


You can use:

ToStringBuilder.reflectionToString(this);

Apache Common Lang contains ToStringBuilder class. You can define different style with ToStringStyle object.

like image 43
y.efe Avatar answered Sep 23 '22 06:09

y.efe


I've had great success doing this on a casual basis using XStream to dump JSON representations of objects. It recurses down objects and just seems to do what you want it to do most of the time. And it's super lightweight. Example:

private static final XStream jsonXStream = 
    new XStream(new JsonHierarchicalStreamDriver());

public static String toDebugString(Object object) {
    return jsonXStream.toXML(object);  
    // ignore "toXML" name, it's going to be JSON.
}
like image 45
HenryTaylor Avatar answered Sep 21 '22 06:09

HenryTaylor