英文:
How does ServiceLoader.load work with class loaders in JPMS?
问题
我有两个JPMS图层:
- 引导图层,使用
ClassLoaders$AppClassLoader@4fca772d
加载模块A
- 子图层,使用
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:
- Boot layer with
module A
loaded byClassLoaders$AppClassLoader@4fca772d
- Child layer with
module B
that provides cervices and loaded byLoader@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
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论