Home >Java >javaTutorial >Can Java Compile and Execute Code from a String?

Can Java Compile and Execute Code from a String?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 13:40:16544browse

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:

  • Compiling arbitrary code can have security implications.
  • Store the Java expression in the database field with appropriate references to variables a and b.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn