Search code examples
javastringexecution

Execute code from a String in Java


I've done some searching, and it seems a few people have asked similar questions, but none of them were quite what I was looking for (some suggested some scripting stuff but i didn't have enough knowledge of what i was doing so i want to use java only if possible).

I need to be able to read lines of code from a String, and then execute them in Java (like this):

String code = "System.out.println(\"Test code\");";

A lot of people reading this post might ask why don't you just execute

System.out.println("Test code");

but I want to execute code other than the println method from Strings.

Is it possible to execute code using java alone, if so how would it compile??


Solution

  • You can't do this as easily as I imagine you hope to. The kind of thing you're describing is something you might see in a dynamic language. Java is very much not a dynamic language - this is part of its character.

    If you have tools.jar in your classpath, you can compile Java code from within your Java program:

    com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
    String[] options = new String[] {
        "-classpath", classpath, "-d", outputDir, filename
    };
    javac.compile(options);
    

    From there you could wrestle with the classloader, load the class you have compiled, and run it.

    However this is not an easy or mainstream way to use Java, and generally people don't do it because it's neither good practice nor necessary. It is a security feature that you can't run code supplied by the user after compilation.


    If you want a more dynamic language, in the Java ecosystem, you could look at Groovy.


    Alternatively, you can run user-supplied Javascript, giving it controlled access to your Java program's data, using the Java Scripting API.