ServiceLoader to find implementations of an interface

主宰稳场 提交于 2019-11-29 22:21:09
axtavt

ServiceLoader cannot do it.

In order to expose class as a service that can be discovered by ServiceLoader you need to put its name into provider configuration file, as described in Creating Extensible Applications With the Java Platform .

There are no built-in ways find all classes that implement a particular interface. Frameworks that can do something similar use their own classpath scanning solutions (and even with custom classpath scanning it's not easy because .class files only store information about interfaces implemented directly, not transitively).

If the implementations are ones that you wrote yourself, you could use AutoService to make them available through the ServiceLoader interface, eg

@AutoService(Operation.class)
class Foo implements FooInterface {

}

@AutoService(Operation.class)
class Bar extends Foo {

}

In order to scan your classpath at runtime for implementations of specific interface you would need to use different solution eg. Reflections (notice s on the end, this is not java's Reflection API)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!