ServiceLoader.load在JPMS中如何与类加载器一起工作?

huangapple go评论62阅读模式
英文:

How does ServiceLoader.load work with class loaders in JPMS?

问题

我有两个JPMS图层:

  1. 引导图层,使用ClassLoaders$AppClassLoader@4fca772d加载模块A
  2. 子图层,使用Loader@6b58b9e9加载提供服务的模块B

Loader@6b58b9e9的父类加载器是ClassLoaders$AppClassLoader@4fca772d

模块A中,我有以下代码:

ServiceLoader<ModuleAInterface> sl = ServiceLoader.load(ModuleAInterface.class);

然而,只有当上下文类加载器为Loader@6b58b9e9时,才能找到模块B的服务,当上下文类加载器为ClassLoaders$AppClassLoader@4fca772d时无法找到。

问题是 - 在这种配置下,是否有可能在模块A中获取到模块B的服务,而无需知道模块B的类加载器。

英文:

I have two JPMS layers:

  1. Boot layer with module A loaded by ClassLoaders$AppClassLoader@4fca772d
  2. Child layer with module B that provides cervices and loaded by Loader@6b58b9e9

The parent classloader of Loader@6b58b9e9 is ClassLoaders$AppClassLoader@4fca772d.

In module A I have the following code:

ServiceLoader<ModuleAInterface> sl = ServiceLoader.load(ModuleAInterface.class);

However, the services of Module B are found only when context class loader is Loader@6b58b9e9 and not found when context class loader is ClassLoaders$AppClassLoader@4fca772d.

The question - is it possible to get services of module B in module A without knowing class loader of module B in such configuration.

答案1

得分: 1

看着jdk 14中java.util.ServiceLoader的代码(见截图),它似乎遵循与在存在多个ModuleLayer时的类加载相同的逻辑,如此stackoverflow答案中所述。

这意味着ServiceLoader会首先查找其自己的ModuleLayer中的服务,然后查找其父ModuleLayer中的服务,并以递归的方式从子到父继续查找。

> 在这种配置下,是否可以在模块A中获取模块B的服务而无需知道模块B的类加载器。

不可以,
但模块B可以看到模块A中的服务。

英文:

looking at the code of java.util.ServiceLoader in jdk 14 (see screenshot) it looks like it follows the same logic as class loading when there are multiple ModuleLayer, as described in this stackoverflow answer

ServiceLoader.load在JPMS中如何与类加载器一起工作?

which means that ServiceLoader will will first look at services in its own ModuleLayer then in its parent ModuleLayer and continue from child to parent in a recursive manner

> is it possible to get services of module B in module A without knowing class loader of module B in such configuration.

no
but module B can see the services in module A

huangapple
  • 本文由 发表于 2020年4月10日 19:19:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61139200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定