Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile Java source code from a string? [duplicate]

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?

like image 495
Tony the Pony Avatar asked Dec 16 '10 17:12

Tony the Pony


People also ask

How do you compile a string in Java?

The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern. compile() method.

How do you run a piece of code in Java?

C++ ProgrammingType 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.


1 Answers

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.)

like image 128
aioobe Avatar answered Oct 06 '22 23:10

aioobe