ServiceLoader 不加载实现

ServiceLoader doesn't load implementation

在问这个问题之前我确实做了很多研究,好像我错过了什么。我尝试实现一个 ServiceLoader,因此做了一个例子 class:

代码很简单:

testInterface.java

package com.test;

public interface testInterface {
    void test();
}

testImpl.java

package com.test;

public class testImpl implements testInterface {

    @Override
    public void test() {
        System.out.println("test");
    }

} 

Main.java

package com.test;

import java.util.ServiceLoader;

public class Main {

    public static void main(String[] args) {
        ServiceLoader<testInterface> serviceLoader = ServiceLoader.load(testInterface.class);

        serviceLoader.iterator().next().test();
    }

}

com.test.testInterface

com.test.testImpl

我一直在迭代器部分收到 NoSuchElementException,这意味着未加载实现。提前致谢。

将您的 META-INF/services/ 放入 resources/ 并将其作为源文件夹添加到 Eclipse 项目中。编译时会自动包含在JAR文件中。