0

有一个接口MyInteface

System 有几个 EAR,每个 EAR 都有自己的接口实现。我需要找到所有没有名称的实现(? extends MyInterface)。

我决定使用java.util.ServiceLoader并创建了一个带有 META-INF/services/com.example.MyInterface 的 jar,这个 jar 可以部署在任何 EAR 中。

jar 在 int 的 init 方法中有一个 servlet 和以下代码:

ServiceLoader<MyInterface > loader = ServiceLoader.load(MyInterface .class);
Iterator<MyInterface > it = loader.iterator();

但是迭代器仍然是空的..

我尝试在 EARs META-INF 中添加 services/com.example.MyInterface,但结果是一样的。

这种方法在 jboss 6 和 tomcat 中运行良好。

4

1 回答 1

3

当我遇到同样的问题时,通过尝试延迟加载解决了

private static class LoaderHolder {
   ServiceLoader<MyInterface > loader = ServiceLoader.load(MyInterface .class);
  }

Iterator<MyInterface > it = LoaderHolder .loader.iterator();
于 2012-11-07T13:54:55.263 回答