mercredi 19 août 2015

how to use recursion in reflection?

I have class test it contains other complex object private class2 e; and that object contains other complex object private class3 b;

public class class3 {
    private String x;
    private String y;
    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
    public String getY() {
        return y;
    }
    public void setY(String y) {
        this.y = y;
    }
}

//class2
public class class2 {
    private String n;
    private class3 b;
    public String getN() {
        return n;
    }
    public void setN(String n) {
        this.n = n;
    }
    public class3 getB() {
        return b;
    }
    public void setB(class3 b) {
        this.b = b;
    }
}
//class test
public class test {
    private String w;
    private class2 e;

    public String getW() {
        return w;
    }

    public void setW(String w) {
        this.w = w;
    }

    public class2 getE() {
        return e;
    }

    public void setE(class2 e) {
        this.e = e;
    }
}

What i need to accomplish is having an Object from test i want to call all getters and if it returns complex object object from other class i want to to go recursively till no complex objects left

i could read all test object data , the part i'm missing is the recessive part

Here is my code :-

private static void writeInLogger(Object obj, String str) {
    Class klazz = obj.getClass();
    if (klazz.isPrimitive() || obj instanceof String
            || obj instanceof Integer || obj instanceof Double
            || obj instanceof Boolean)
        System.out.println(str + obj.toString());
    else {
        try {
            for (PropertyDescriptor propertyDescriptor : Introspector
                    .getBeanInfo(klazz).getPropertyDescriptors()) {
                Method m = propertyDescriptor.getReadMethod();
                if (m != null){
                Object object = m.invoke(obj);
                    Class klazz2 = object.getClass();
                    if(klazz2.isPrimitive() || object instanceof String|| object instanceof Integer || object instanceof Double|| object instanceof Boolean){
                        System.out.println(m + str + m.invoke(obj).toString());
                    }

                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire