Search code examples
javajvmclassloader

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())?


Solution

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

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