简体   繁体   中英

How to find all (child) sub-interfaces of a particular interface in Java?

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 ? Ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM