Home >Java >javaTutorial >Can Java Compile and Execute Code from a String?
Compiling Dynamic Code from a String
Question:
Can a String containing code be converted into a format that can be compiled and executed in Java?
Answer:
Yes, using the Java Compiler API. Here's how:
In Java 6 or later, utilize the JavaCompiler class to compile code dynamically.
Code:
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();
Note:
The above is the detailed content of Can Java Compile and Execute Code from a String?. For more information, please follow other related articles on the PHP Chinese website!