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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6616055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:38:30  来源:igfitidea点击:

get all (derived) interfaces of a class

javareflection

提问by markdsievers

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

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.

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

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

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

我可以自己写这个,但我确定必须存在一个已经这样做的图书馆,有什么想法吗?

回答by Alex Gitelman

回答by markdsievers

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.

这是一个比古老的 Apache 东西更强大、更干净的反射 API。

回答by Igor Rybak

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

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