ServiceLoader查找接口的实现 [英] ServiceLoader to find implementations of an interface

查看:39
本文介绍了ServiceLoader查找接口的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Java ServiceLoader 查找实现特定接口的所有类,如下所示:

I tried to use the Java ServiceLoader to find all classes that implement a specific interface like so:

loader = ServiceLoader.load(Operation.class);
try {
    for (Operation o : loader) {
        operations.add(o);
    }
} catch (ServiceConfigurationError e) {
    LOGGER.log(Level.SEVERE, "Uncaught exception", e);
}

不幸的是,当我在调试模式下运行Eclipse时,ServiceLoader找不到任何类.我觉得我想念一点琐事...

Unfortunately, when I run Eclipse in debug mode the ServiceLoader doesn't find any classes. I feel like I'm missing a trivial point...

推荐答案

ServiceLoader 无法做到.

为了将类公开为可由 ServiceLoader 发现的服务,您需要将其名称放入提供程序配置文件中,如

In order to expose class as a service that can be discovered by ServiceLoader you need to put its name into provider configuration file, as described in Creating Extensible Applications With the Java Platform .

没有内置的方法可以找到实现特定接口的所有类.可以执行类似操作的框架使用其自己的类路径扫描解决方案(即使使用自定义类路径扫描也不容易,因为 .class 文件仅存储有关直接实现的接口的信息,而不是可传递的).

There are no built-in ways find all classes that implement a particular interface. Frameworks that can do something similar use their own classpath scanning solutions (and even with custom classpath scanning it's not easy because .class files only store information about interfaces implemented directly, not transitively).

这篇关于ServiceLoader查找接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆