1

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.

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
  • You need a way to check if a type is a class or an interface. Or you need a way to load all types (classes and interfaces) and check one by one if they are interfaces exteding "A" ? – Davide Lorenzo MARINO Nov 20 '15 at 11:44
  • I know that it's not exactly what you asked, but does it solve your problem? http://stackoverflow.com/questions/347248/how-can-i-get-a-list-of-all-the-implementations-of-an-interface-programmatically – Paulo Nov 20 '15 at 11:46
  • @Paulo Unfortunately that answer is the wrong way round - it is finding parent interfaces rather than child interfaces. – Steve Chambers Nov 20 '15 at 11:57
  • @DavideLorenzoMARINO Yes, but was hoping this might have been done somewhere before (perhaps by Spring, Google Reflections or some other library...) – Steve Chambers Nov 20 '15 at 11:59

1 Answers1

5

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
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • Nice but it seems to be not working when this is not a direct extends. i.e. : interface C extends B instead of A – Jos Jan 04 '17 at 07:44
  • @Jos For sure. The requirement was to find the direct subinterfaces of a given interface. If you want to find all classes/interfaces implementing a given interface then consume the result provided in `subTypes`. – SubOptimal Jan 04 '17 at 13:16