开发者

get all (derived) interfaces of a class

java.lang.Class.getInterfaces returns all directly implemented interfaces ie doesn't walk the class tree to ge开发者_C百科t 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?


Apache Commons Lang has method you need: ClassUtils.getAllInterfaces


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.


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


public interface A {}

public interface B {}

public interface E extends B{ }

public class C implements A{}

public class D extends C implements E{}

get all (derived) interfaces of a class

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();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜