代码之家  ›  专栏  ›  技术社区  ›  m_pGladiator

如何使java ServiceLoader在NetBeans 6.9模块应用程序中工作

  •  3
  • m_pGladiator  · 技术社区  · 15 年前

    我在NetBeans模块应用程序中使用java ServiceLoader时遇到了问题。下面是我要做的(它在Eclipse中的普通java应用程序中工作):

    private static List<MyInterface<?>> loadAllImplementations() {
        List<MyInterface<?>> foundImplementations = Lists.newArrayList();
        try {
            for (MyInterface implementation : ServiceLoader.load(MyInterface.class)) {
                foundImplementations.add(implementation);
            }
        } catch (ServiceConfigurationError error) {
            system.out.println("Exception happened");
        }
        return foundImplementations;
    }
    

    但是在NetBeans下,它找不到任何东西(foundImplementations.size()=0)。

    更多详细信息:

    public static final <T> MyInteface<T> getByName(String name) {
        for (MyInteface implementation : loadAllImplementations()) {
            if (implementation.getName().equals(name)) {
                return implementation;
            }
        }
    
        throw new IllegalArgumentException("Unable to find MyInterface class for: " + name);
    }
    

    我对NetBeans的了解非常有限,我想知道为了让它正常工作,我还需要做些什么吗?

    3 回复  |  直到 15 年前
        1
  •  2
  •   FabienB    14 年前

    为了工作,您必须让Netbeans在META-INF中创建这个服务子文件夹。这很容易做到,但是信息很容易访问。

    要向META-INF添加内容,您需要在src/(源目录[spi?])文件夹中创建一个同名文件夹。在这种情况下,您还需要services文件夹,并在其中创建一个与服务接口具有相同完全限定名的文本文件。最后,您应该有这样的结构:src/META-INF/services/my.package.MyInterface。

    最后,这个[my.package.MyInterface]文件的内容应该列出所有实现类(每行一个)。

    通过这种设置,Netbeans将在构建应用程序时创建适当的jar。

    看一看 this ServiceLoader 例子。这是一个完整的示例,尽管它没有解释我刚才描述的Netbeans集成。

        2
  •  0
  •   naikus    15 年前

    为此,您可能需要尝试不同的方法:

    • 您可能需要创建一个类加载器(可能是类路径中包含这些jar的URLClassLoader)并使用 ServiceLoader.load(Class, ClassLoader) 传递一个类加载器。
    • here

    很可能handler.jar和implementations.jar不是由同一个类加载器加载的。此外,您可能想看看为什么您的文件会进入ext文件夹。

    希望这有帮助。

    • 也试着打电话给 ServiceLoader.load(Class, null) 它使用系统类加载器(启动应用程序的加载器)。类加载器可能能够在ext目录中的jar中找到类。
        3
  •  0
  •   m_pGladiator    15 年前

    JSPF . 这是开箱即用的,我不需要知道作为NetBeans模块编写的第三方程序的内部结构,也不需要知道它如何影响提供给类装入器的类路径。