In my program I'm trying to compile and run some java code, that I get from a TextField, when I click a button. To compile the code, i use:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector diagnostics = new DiagnosticCollector();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList("Code.java"));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
boolean succ = task.call();
Then I'm calling the main method of my code.class class
Code.main(new String[0]);
The first time i compile and run the code via a button click, it works fine, but when I change the code in the TextField and compile and run it again, it doesn't update, but the old code runs.
答案 0 :(得分:0)
您似乎在与调用程序相同的JVM中运行已编译的程序(code
)?如果是这样,请记住,只要JVM加载了一个类,该类就要保留。您需要应用一些类加载器魔法才能“忘记”以前的版本,并在重新编译后加载新版本。
这里的“魔术”可以简单如下:
注1:您没有显示调用main
的确切顺序,但显然您需要使用反射来调用编译应用程序时不存在的代码。
注2:根据惯例,code
将是变量的名称。如果这应该是一个类的名称,那么如果你使用类拼写/大写字母会更清楚:Code
。