1
所以我有一些代碼 - 我想編譯字符串'temp'然後執行它,然後更改字符串,重新編譯並執行。問題是目前它只是首先執行第一個代碼。在代碼中編譯,沒有得到我想要的行爲。
我想到:
我也得到:
This is in another java file
This is in another java file
的完整代碼如下,感謝任何幫助。
import java.io.IOException;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
public class Another2 {
public static void main(String args[]) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
//First run
String temp = "public class HelloWorld {\n" + " public static void main(String args[]) {\n"
+ " System.out.println(\"First Compiled Class\");\n" + " }\n" + "}";
JavaFileObject file = new JavaSourceFromString("HelloWorld", temp);
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
task.call();
try {
Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class })
.invoke(null, new Object[] { null });
} catch (Exception e) {
// handled it
}
//second run
temp = "public class HelloWorld {\n" + " public static void main(String args[]) {\n"
+ " System.out.println(\"How About Now?\");\n" + " }\n" + "}";
file = new JavaSourceFromString("HelloWorld", temp);
Iterable<? extends JavaFileObject> compilationUnits2 = Arrays.asList(file);
task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits2);
task.call();
try {
Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class })
.invoke(null, new Object[] { null });
} catch (Exception e) {
// handled it
}
}
}