trung / InMemoryJavaCompiler

Utility class to compile java source code in memory
Apache License 2.0
266 stars 81 forks source link

ClassLoader failed to find class with its qualified name after compiled successfully #28

Closed ghost closed 5 years ago

ghost commented 5 years ago

Problem

I try to compile the source code of a project.

All java files under the src/main/java directory is stored in to InMemoryJavaCompiler#addSource(String className, String sourceCode). And the className is qualified name, e.g. org.mdkt.compiler.CompiledCode, because there may be classes with the same simple name, e.g. CompiledCode, but in different package.

However, when I called InMemoryJavaCompiler#compileAll(), the classLoader failed to find the compiled class because the it stored it with simple name but search with the qualified name.

public Map<String, Class<?>> compileAll() throws Exception {
            ...

            Map<String, Class<?>> classes = new HashMap();
            Iterator var15 = this.sourceCodes.keySet().iterator(); //the key is qualified name

            while(var15.hasNext()) {
                String className = (String)var15.next();
                //the name stored in classLoader is simple name, therefore, it cannot find the class
                classes.put(className, this.classLoader.findClass(className)); 
            }

            return classes;
        }

ScreenShots

Screenshot 2019-05-03 at 6 41 36 PM

Related issue

https://github.com/trung/InMemoryJavaCompiler/issues/17