java 如何在类路径中找到接口的所有实现?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3123095/
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 00:27:44  来源:igfitidea点击:

How can I find all implementations of interface in classpath?

javareflection

提问by newbie

I'm implementing an interface and now I'd like to get all implementations of this interface in classpath. Is this possible or should I do something else?

我正在实现一个接口,现在我想在类路径中获得这个接口的所有实现。这是可能的还是我应该做其他事情?

采纳答案by Stephen C

At best, this will be expensive. At worst (depending on the classloaders) it may be impossible.

充其量,这将是昂贵的。在最坏的情况下(取决于类加载器),这可能是不可能的。

I strongly suggest that you look for an alternative approach to the underlying problem that you are trying to address.

我强烈建议您寻找一种替代方法来解决您试图解决的潜在问题。

回答by Bozho

The Reflectionslibrary will let you do that (to an extent):

思考图书馆将让你这样做(在一定程度上):

Set<Class<? extends SomeClassOrInterface>> subTypes = 
     reflections.getSubTypesOf(SomeClassOrInterface.class);

However I wouldn't recommend that. Imagine a typical classpath with 50 external jars, each of which being a big framework like spring, hibernate, aspectj, jsf, etc. It would take much time.

不过我不建议这样做。想象一个典型的类路径,有 50 个外部 jar,每个都是一个大框架,如 spring、hibernate、aspectj、jsf 等。这将花费很多时间。

If you want to have some kind of plugin mechanism, so that others can implement your interfaces and supply jars with the implementation, then look at java.util.ServiceLoader

如果您想拥有某种插件机制,以便其他人可以实现您的接口并提供带有实现的 jar,那么请查看java.util.ServiceLoader