Dahakka
Dahakka

Reputation: 277

java get all extended interfaces from base interface

Is it possible to get list of all interfaces which extends base interface without having any bean implemented any interface in java at runtime?

Example:

interface A {}
interface B extends A{}
interface C extends A{}
interface D extends C{}

public Class<? extends A>[] getAllInterfaces(A.class);

Method getAllInterfaces() should return all interfaces which extends A: {B, C, D}

Upvotes: 4

Views: 1787

Answers (2)

Aleh Maksimovich
Aleh Maksimovich

Reputation: 2650

Provided that you don't need to do your scanning with pure reflection you can use Reflections library to do the scanning.

The basic variant that checks for the descendent interfaces on the same class loader will be:

public <T> Class<? extends T>[] getAllInterfaces(Class<T> clazz) {

    Reflections reflections = new Reflections(clazz.getClassLoader());

    return reflections.getSubTypesOf(clazz)
            .stream()
            .filter(subClass -> subClass.isInterface())
            .toArray(Class[]::new);
}

The code above should be updated based on how do you understand "all types". You may need to add class loaders or do some other adjustments.

Upvotes: 1

Sebastian Redl
Sebastian Redl

Reputation: 71909

Kind of, but not really.

What you would have to do is enumerate all types, and among them find things that are interfaces and extend your interface. (Use Class#isInterface and Class#getInterfaces.)

However, the real difficulty is in finding "all types". Does that mean all types currently loaded by the JVM? Does it mean all types that can be found on the current classpath? You could load classes from basically any source, so the theoretical set of interfaces that extend your interface is infinite.

There is no standard way of doing any of these enumerations, by the way. For the first variant, see this thread: Java - Get a list of all Classes loaded in the JVM

Upvotes: 3

Related Questions