简体   繁体   中英

java.lang.ClassCastException when using custom classloader

I need to dynamically load a java class at runtime. For this purpose I'm using https://github.com/trung/InMemoryJavaCompiler .

The class that I need to load implements an interface that already is part of my application (this interface is therefore loaded by system-classloader). After the class is loaded, I cast it to the interface.

UPDATE : Sorry, but I was wrong about docker. That has of course nothing to do with docker, but with the fact that I'm starting the application via command line: java -jar ... . When the application is started from intellij it works. When it's started via command line java.lang.ClassCastException is thrown when I try to cast.

The class loader of the real interface is org.springframework.boot.loader.LaunchedURLClass Loader@2a84aee7 while the class loader of the dynamically loaded interface is sun.misc.Launcher$AppClassLoader@55f96302. Thank you for helping me identifying the problem.

What could I do to ensure that the same class loader is used?

Would it be a good idea to always make the custom class loader child of the interface's class loader: new DynamicClassLoader(MyInterface.class.getClassLoader()) ?

Yes, DynamicClassLoader needs to delegate to the ClassLoader that loads MyInterface .

new DynamicClassLoader(MyInterface.class.getClassLoader()) should be fine.

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.

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