Pregunta

Ok, so I have a program where the user gets to write .java files, and execute it (during runtime....duh!!). Currently, the user can edit only one .java file (for now). Now I want to compile the .java file and make it into a .class file. To run the file, I expect the user to have a void main() function, and I simply execute that function to run it. So, i have made the .java file editable using a JTextArea, BufferedReader, BufferedWriter, etc. Now the code I have written to compile the file is:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
    Iterable<? extends JavaFileObject> compilationUnits = filemanager.getJavaFileObjectsFromStrings(Arrays.asList("src/User/Script.java"));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
    boolean success = task.call();
    System.out.println(success);
} catch(IOException e){
    System.out.println("IOException");
}

The code compiles the file to a .class file. Now when I execute the main function from it, it does not work. In fact, the value of success is true (as it prints true). Once this is done, the user presses the "Run" button and I use this to run the function :

Script script = new Script(); script.main();

Now for some reason, the script does not update itself. It still executes the same thing that was written before the script was modified....although the file is written as expected, but the script some sort of "updates" only the next time the program is launched. (I haven't tried this as a standalone,but it updates in the IDE...which is Netbeans).

Now I not only need the solution to this problem, but I would also like an explanation to what is being done. Please, give me an explanation as to what is wrong, why it is wrong and what needs to be done to fix it.

Regards,
Rakshith

¿Fue útil?

Solución

The problem here is the class is already loaded to JVM. You must unload the Class and reload the new version. It should work if the class didn't exist before launching the application.

You must create your own classloader for such a thing to work, this is for sure a difficult task, I am not aware of any library/tool for that, apart from javassist.

A nice hack would be to rename your desired class or maybe the package, but I am not sure if this is acceptable for you.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top