gpt4 book ai didi

java - 为什么 JPMS 允许注解类型作为服务

转载 作者:行者123 更新时间:2023-12-04 14:37:42 33 4
gpt4 key购买 nike

在介绍 JPMS 服务时,Java 语言规范第 7.7.4 节指出“服务类型必须是类类型、接口(interface)类型或注解类型”。

我很难看到允许注释的意义。我的理解是,JPMS 的服务概念是我们希望在运行时选择实现的东西。看起来,为了有用,实现至少需要有可能成为标识所请求服务的原始类以外的东西。但我相信注释不能使用“扩展”,所以这永远不会发生?从那时起,我相信如果我尝试从注释类型中创建服务,我将不可避免地遇到这样一种情况,即唯一可以通过服务查找返回的东西,例如 SomeAnnotation。类将完全是 SomeAnnotation。这似乎毫无意义,所以我必须假设我错过了一些东西。

任何人都可以阐明这一点,并可能提供注释如何成为“服务”的示例?

最佳答案

您似乎错过了服务提供商的另一个补充。在命名模块中,服务提供者可以从静态方法返回实现:

  • If the service provider declares a provider method, then the service loader invokes that method to obtain an instance of the service provider. A provider method is a public static method named "provider" with no formal parameters and a return type that is assignable to the service's interface or class.

    In this case, the service provider itself need not be assignable to the service's interface or class.



来自 ServiceLoader

因此,以下将起作用:
module Example.Module {
uses example.Anno;
provides example.Anno with example.AnnoProvider;
}
package example;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {
int value();
}
package example;

@Anno(42)
public class AnnoProvider {
public static Anno provider() {
return AnnoProvider.class.getAnnotation(Anno.class);
}
}
package example;

import java.util.ServiceLoader;

public class ServiceUser {
public static void main(String[] args) {
for(Anno a: ServiceLoader.load(Anno.class)) {
System.out.println(a.value());
}
}
}

关于java - 为什么 JPMS 允许注解类型作为服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593407/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com