2016-05-13 268 views
0

加载一个由两个不同的类加载器实例化的对象时遇到问题。基本上我实现了一个带有三个不同插件的webapp,每个插件都有自己的类加载器。项目结构如下:如何使用两个不同的类加载器加载同一个类

MyAppService 
- ObjectInterface.java 
MyAppImpl 
- ObjectImplementation.java 
MyClass 
- MyClass.java 

它是一个基于maven的项目。 MyAppImplMyClass都具有MyAppService作为依赖性。现在,我使用此代码创建类ObjectImplementation中类ObjectImplementation的对象。

ObjectInterface o = new ObjectImplementation(); 

我想这个对象传递给方法在Myclass类,在这里我得到这个代码的对象。

ObjectInterface o = (ObjectInterface) passedObject; 

但我得到了异常java.lang.ClassCastException: MyAppImpl.ObjectImplementation cannot be cast to MyAppService.ObjectInterface。我也尝试动态类加载与代码

ObjectInterface o = (ObjectInterface) Class.forName("MyAppImpl.ObjectImplementation").newInstance(); 

但我得到例外java.lang.ClassNotFoundException: MyAppImpl.ObjectImplementation。添加MyAppImpl作为MyClass的依赖项目前不是一种选择。有谁知道我的问题是否有解决方案?

回答

0

请阅读ClassLoaders及其层次结构。还请阅读有关委派机制。

在你的情况,类由叶类加载器加载,并有相同类的不同副本。如果特定类未被当前类加载器或其父类加载,那么您将获得java.lang.ClassCastException

相关问题