javacompilation

Compile Java source code from a string?


Is there a way for a running Java program to compile Java source code (passed as a string)?

Class newClass = Compiler.compile ("class ABC { void xyz {etc. etc. } }");

Ideally, any classes referenced by the passed-in source code would be resolved by the program's class loader.

Does something like this exist?


Solution

  • Sure. Have a look at the JavaCompiler class and the other classes in the javax.tools package.

    They've been around since Java 1.6.

    Here is some example code.

    (As pointed out by @Sergey Tachenov in the comments, it needs JDK to be installed as the necessary tools.jar file comes with JDK but not JRE.)