简体   繁体   English

ClassLoader:两个ClassLoader及其类之间的访问级别

[英]ClassLoader: Access level between two ClassLoaders and their classes

following scenario: 以下情况:

  • CustomClassLoaderA loads ClassA CustomClassLoaderA加载ClassA
  • CustomClassLoaderB loads ClassB CustomClassLoaderB加载ClassB

so far so good, but: 到目前为止一切顺利,但是:

  • CustomClassLoaderA should be able to access ClassB CustomClassLoaderA应该能够访问ClassB
  • CustomClassLoaderB should be able to access ClassA CustomClassLoaderB应该能够访问ClassA

Does anyone have an idea how I can accomplish this scenario in Java? 有谁知道如何用Java完成此方案? One more restriction is that the two CustomClassLoader are on the same level. 另一个限制是两个CustomClassLoader处于同一级别。 Say, they have the same parent ClassLoader. 说,他们有相同的父ClassLoader。

Thank you very much in advance, guys! 伙计们,非常感谢您!

I don't think this is possible since any normal class loader implementation follows parent-first policy and they almost never look towards siblings for loading classes. 我认为这是不可能的,因为任何普通的类加载器实现都遵循父级优先策略,并且他们几乎从不希望兄弟姐妹加载类。 I think separate class loaders are typically used to separate run time for different modules/applications so that they don't conflict in namespaces. 我认为通常使用单独的类加载器来分隔不同模块/应用程序的运行时,以便它们在命名空间中不会发生冲突。 I wouldn't want to design custom class loaders which undermine this basic idea. 我不想设计破坏该基本思想的自定义类加载器。

That said, I think there is a brilliant way to achieve this using interfaces and factory pattern. 就是说,我认为有一种绝妙的方法可以使用接口和工厂模式来实现。 Let us say, ClassA implements InterfaceA and there is a factory called AFactory which creates/spits out objects of InterfaceA . 让我们说, ClassA实现InterfaceA并且有一个名为AFactory的工厂可以创建/吐出InterfaceA对象。

We'll have to make sure the classes InterfaceA and AFactory are both loaded by the parent class loader. 我们必须确保类InterfaceAAFactory都由父类加载器加载。

Then CustomClassLoaderA , registers an object of ClassA with the AFactory (probably at start-up): 然后CustomClassLoaderA ,寄存器的一个目的ClassAAFactory (可能在启动时):

AFactory aFactory = AFactory.getInstance():
aFactory.registerA(new ClassA());

Then the code that executs in CustomClassLoaderB gets an instance of ClassA , by the following code: 然后,通过以下代码在CustomClassLoaderB执行的代码获得ClassA的实例:

AFactory aFactory = AFactory.getInstance();
InterfaceA a = aFactory.getA()
a.invokeMethodInA();

Similar code can be written for sharing objects of ClassB with CustomerClassLoaderA . 可以编写类似的代码来与CustomerClassLoaderA共享ClassB对象。

Note that classes cannot be shared across incompatible class loaders, but object instances can. 请注意,不能在不兼容的类加载器之间共享类,但是对象实例可以共享。 So, once the object is created, there should be no problem in tossing it around different class loaders, as long as there is a common interface (or LHS) to type cast it to. 因此,一旦创建了对象,只要有一个通用的接口(或LHS)将其类型转换为对象,就可以将它扔到不同的类加载器中没有问题。

You can also use abstract classes instead of interfaces. 您也可以使用抽象类代替接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM