Given an interface:
public interface A {};
with inheriting interfaces:
public interface B extends A {}
public interface C extends A {}
How can I programmatically scan to find B
and C
? I.e. how to do this:
Type[] types = findAllSubInterfacesOfA(); // Returns [B.class, C.class]
Note: Am trying to find interfaces here, not classes or instances.
Following snippet should do it.
public class FindSubinterfaces {
public static void main(String[] args) {
Class clazz = A.class;
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(Arrays.asList(ClasspathHelper.forClass(clazz))));
Set<Class<? extends List>> subTypes = reflections.getSubTypesOf(clazz);
for (Class c : subTypes) {
if (c.isInterface()) {
System.out.println("subType: " + c.getCanonicalName());
}
}
}
}
interface A {
};
interface B extends A {
}
interface C extends A {
}
class CA implements A {
}
abstract class DC implements C {
}
output
subInterface: sub.optimal.reflections.B
subInterface: sub.optimal.reflections.C