markdsievers
markdsievers

Reputation: 7309

get all (derived) interfaces of a class

java.lang.Class.getInterfaces returns all directly implemented interfaces ie doesn't walk the class tree to get all interfaces of all parent types. eg For example the hierarchy

public interface A {}
public interface B {}
public interface C extends B {}

public class Foo implements A {} // Foo.class.getInterfaces() returns [A]
public class Bar implements C {} // Bar.class.getInterfaces() returns [C], note B is not included.

For Bar I would like to get [B, C], but for any arbitrary tree depth.

I could write this myself, but I'm sure a library must exist that does this already, any ideas?

Upvotes: 45

Views: 26568

Answers (5)

Lovro Pandžić
Lovro Pandžić

Reputation: 6380

public Stream<Class<?>> getInterfaces(Class<?> type) {
    return Stream.of(type.getInterfaces())
                 .flatMap(interfaceType -> Stream.concat(Stream.of(interfaceType), getInterfaces(interfaceType)));
}

Upvotes: 3

Mami Alexandre
Mami Alexandre

Reputation: 121

public interface A {}

public interface B {}

public interface E extends B{ }

public class C implements A{}

public class D extends C implements E{}

enter image description here

public class App {

    public static void main(String[] args) {

        final List<Class<?>> result = getAllInterfaces(D.class);            
        for (Class<?> clazz : result) {
            System.out.println(clazz);
        }
    }

    public static List<Class<?>> getAllInterfaces(Class<?> clazz) {
        if (clazz == null) {
            System.out.println(">>>>>>>>>> Log : null argument ");
            return new ArrayList<>();
        }
        List<Class<?>> interfacesFound = new ArrayList<>();
        getAllInterfaces(clazz, interfacesFound);
        return interfacesFound;
    }

    private static void getAllInterfaces(Class<?> clazz,
                                         List<Class<?>> interfacesFound) {
        while (clazz != null) {
            Class<?>[] interfaces = clazz.getInterfaces();

            for (int i = 0; i < interfaces.length; i++) {
                if (!interfacesFound.contains(interfaces[i])) {
                    interfacesFound.add(interfaces[i]);
                    getAllInterfaces(interfaces[i], interfacesFound);
                }
            }
            clazz = clazz.getSuperclass();
        }
    }
}

Upvotes: 0

Ihor Rybak
Ihor Rybak

Reputation: 3279

Don't forget, Spring Framework has many similar util classes like Apache Commons Lang. So there is: org.springframework.util.ClassUtils#getAllInterfaces

Upvotes: 8

user177800
user177800

Reputation:

Guava Solution:

final Set<TypeToken> tt = TypeToken.of(cls).getTypes().interfaces();

This is a much more powerful and cleaner reflection API than the ancient Apache stuff.

Upvotes: 23

Alex Gitelman
Alex Gitelman

Reputation: 24722

Apache Commons Lang has method you need: ClassUtils.getAllInterfaces

Upvotes: 53

Related Questions