I use Java compiler class inside my Spring Boot application as follows:
String classStr = "\n" +
"import java.util.List;\n" +
"import java.util.Map;\n" +
"import java.util.Arrays;\n"+
"public class TestClass {\n" + String.join("\n",methods) + "}";
File root = new File("/src/main/resources/");
File sourceFile = new File(root, "TestClass.java");
sourceFile.getParentFile().mkdirs();
Files.write(sourceFile.toPath(), classStr.getBytes(StandardCharsets.UTF_8));
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null,sourceFile.getPath());
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{root.toURI().toURL()});
cls = Class.forName("TestClass", true, classLoader);
It is working as expected and cls
methods can be invoked without any problem.
Then I try to import and use a class inside my project src as follows:
String classStr = "\n" +
"import java.util.List;\n" +
"import java.util.Map;\n" +
"import java.util.Arrays;\n"+
"import com.nilanka.compilertest.Utility;\n"+
"public class TestClass {\n" + String.join("\n",methods) + "}";
It gave me the error at the start:
Caused by: java.lang.ClassNotFoundException: Utility
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
Then I tried:
compiler.run(null, null, null,
-cp",Utility.class.getProtectionDomain().getCodeSource().getLocation().getPath(),sourceFile.getPath());
then Application started without any error.
But when I try to execute a method from new class:
java.lang.NoClassDefFoundError: com/nilanka/compilertest/Utility
How can I resolve this problem?
I need a way to make the imports available in both compiling and runtime for the class.