user2547836 user2547836 - 3 months ago 16
Java Question

How to use reflections library to get subtype of a subtype

Here is my scenario, I have three classes:

public abstract class A {

public Set<Class<?>> getGrandChildren() {
Reflections reflections = new Reflections(this.getClass().getPackage().getName());
Set<Class<?>> grandChildren = reflections.getSubTypesOf(this.getClass());
return grandChildren;
}

}

public class B extends A {}

public class C extends B implements X {}

class D {

public B client = new B();

//I am trying to get all children of this class
client.getGrandChildren()
}


My compiler complains about type of:

Set<Class<?>> grandChilderen = reflections.getSubTypesOf(this.getClass());


How do I go about this?

Answer

The easiest way is to rely on the raw type as it fails because it expects a value for the parameterized type (corresping to T in the signature public <T> Set<Class<? extends T>> getSubTypesOf(Class<T> type)) which you cannot provide here as it is a generic method

public Set<Class<?>> getGrandChildren() {
    Reflections reflections = new Reflections(this.getClass().getPackage().getName());
    Set grandChildren = reflections.getSubTypesOf(this.getClass());
    return grandChildren;
}