在问这个之前我真的做了很多研究,好像我错过了什么。我尝试实现一个 ServiceLoader,因此制作了一个示例类:
代码很简单:
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 文件中。
关于java - ServiceLoader 不加载实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425488/