從字串編譯動態程式碼
問題:
包含程式碼的字串可以是轉換為可以編譯執行的格式Java?
答案:
是的,使用 Java 編譯器 API。具體方法如下:
在 Java 6 或更高版本中,利用 JavaCompiler 類別動態編譯程式碼。
程式碼:
String comparableClassName = ...; String comparatorClassName = ...; String source = "public class " + comparatorClassName + " implements Comparable<" + comparableClassName + "> {" + " public int compare(" + comparableClassName + " a, " + comparableClassName + " b) {" + " return " + expression + ";" + " }" + "}"; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); /* * Refer to the JavaCompiler JavaDoc page for examples of the following objects (most can remain null) */ Writer out = null; JavaFileManager fileManager = null; DiagnosticListener<? super JavaFileObject> diagnosticListener = null; Iterable<String> options = null; Iterable<String> classes = null; Iterable<? extends JavaFileObject> compilationUnits = new ArrayList<>(); compilationUnits.add( new SimpleJavaFileObject() { // See JavaDoc page for more details on loading the source String } ); compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits).call(); Comparator comparator = (Comparator) Class.forName(comparableClassName).newInstance();
注意:
以上是Java 可以編譯並執行字串中的程式碼嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!