从字符串编译动态代码
问题:
包含代码的字符串可以是转换为可以编译和执行的格式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中文网其他相关文章!