I am currently doing a project for my university. I work on an application that allows a user to type java methods into a text area. The application then puts these methods into a class and should compile it when the user hits the compile button.
So far I used this approach: https://stackoverflow.com/a/2946402
And it worked for me at first, but it only compiles a simple (standalone) class. The class I have to compile at runtime extends another class from the application. In this way the user should get access to some methods from the super class, which I implemented. This is the method I use to compile the class:
public Class<?> loadClass(String filename) {
WorkingDirectory workingDirectory = WorkingDirectory.getInstance();
File directory = workingDirectory.getCompileDirectory();
File javaFile = workingDirectory.createJavaFileFromUserProgram(filename);
Class<?> cls = null;
try {
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, javaFile.getPath());
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { directory.toURI().toURL() });
cls = Class.forName(filename, true, classLoader);
} catch (Exception e) {
e.printStackTrace();
}
return cls;
}
This works fine with a class that does'nt extend anything. When I add the extends I end up with this error message:
error: cannot find symbol
public class UsersClass extends ExistingClass { public void main() {
^
symbol: class ExistingClass
1 error
java.lang.ClassNotFoundException: UsersClass
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at utils.SimulatorClassloader.loadClass(SimulatorClassloader.java:51)
at simulator.Simulator.lambda$4(Simulator.java:171)....
Does someone know what I need to add/change in my method? I did some research for several hours, but I didn't make progress since then.