I have a problem with loading an object which is instantiated by two different classloaders. Basically I implement a webapp with three different plugins, each with its own classloader. The project structure looks like this:
MyAppService
- ObjectInterface.java
MyAppImpl
- ObjectImplementation.java
MyClass
- MyClass.java
Its a maven based project. MyAppImpl
and MyClass
both have MyAppService
as a dependency. Now I use this code to create an object of class ObjectImplementation
in class ObjectImplementation
.
ObjectInterface o = new ObjectImplementation();
I want to pass this object to a method in class Myclass
, where I get the object with this code.
ObjectInterface o = (ObjectInterface) passedObject;
But I get the exception java.lang.ClassCastException: MyAppImpl.ObjectImplementation cannot be cast to MyAppService.ObjectInterface
. I also tried dynamic class loading with the code
ObjectInterface o = (ObjectInterface) Class.forName("MyAppImpl.ObjectImplementation").newInstance();
but I get the exception java.lang.ClassNotFoundException: MyAppImpl.ObjectImplementation
. Adding MyAppImpl as a dependency for MyClass is currently not an option. Does anyone know if there is a solution for my problem?
Please read about ClassLoaders and its hierarchy. Also read about delegation mechanism.
In your case, classes are loaded by leaf classloaders and there are different copies of the same class. If the particular class is not loaded by current class loader or any of its parent then you will get the java.lang.ClassCastException
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.