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

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

 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. 

对于Bar我想得到[B, C] ,但是对于任意的树深度。

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

Apache Commons Lang有你需要的方法: ClassUtils.getAllInterfaces

番石榴解决scheme:

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

这是一个比古代的Apache东西更强大和更清晰的reflectionAPI。

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