ServiceLoader to find implementations of an interface

后端 未结 3 2217
孤街浪徒
孤街浪徒 2020-12-24 03:39

I tried to use the Java ServiceLoader to find all classes that implement a specific interface like so:

loader = ServiceLoader.load(Operation.class);
try {
           


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 03:53

    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).

提交回复
热议问题