【问题标题】:ServiceLoader doesn't load implementationServiceLoader 不加载实现
【发布时间】:2015-10-29 22:08:57
【问题描述】:

在问这个之前我真的做了很多研究,好像我错过了一些东西。我尝试实现一个 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,这意味着未加载实现。提前致谢。

【问题讨论】:

    标签: java serviceloader


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答,我知道事情会这么简单。我在其他视频/帖子中看到了这个项目结构,并认为它是正确的,似乎是错误的。非常感谢!
    • 我刚遇到这个问题;如果其他人也有它,请确保链接资源/目录时,它包含该类型的文件。我花了很长时间才弄清楚;谢谢 Eclipse!
    • 如果您使用模块,请确保在您的module-info.java 中添加providesuses 语句,否则您会遇到相同的NoSuchElementException!如果上面的例子包含在一个模块中,你需要添加:provides com.test.testInterface with com.test.testImpl;uses com.test.testInterface;
    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2018-09-13
    相关资源
    最近更新 更多