获取类的所有(派生)接口

mar*_*ers 38 java reflection

java.lang.Class.getInterfaces返回所有直接实现的接口,即不遍历类树以获取所有父类型的所有接口.例如,层次结构

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.
Run Code Online (Sandbox Code Playgroud)

因为Bar我想得到[B, C],但对于任意树深度.

我自己可以写这个,但我确定一个图书馆必须存在才能做到这一点,任何想法?

小智 17

番石榴解决方案:

final Set<TypeToken> tt = TypeToken.of(cls).getTypes().interfaces();
Run Code Online (Sandbox Code Playgroud)

这是一个比古代Apache更强大,更清晰的反射API.


Igo*_*bak 5

别忘了,Spring Framework有很多类似的 util 类,比如 Apache Commons Lang。所以有:org.springframework.util.ClassUtils#getAllInterfaces