5

在问这个之前我真的做了很多研究,似乎我错过了一些东西。我尝试实现一个 ServiceLoader 并因此制作了一个示例类:

项目结构

代码很简单:

测试接口.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");
    }

} 

主.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,这意味着未加载实现。提前致谢。

4

1 回答 1

9

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

于 2015-10-29T22:51:21.187 回答