Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating, compiling and using Java code at run time?

I have a scenario where I have to generate Java code when my application is running.

Can compile and run than code from my application( as a separate application).

Is it possible to compile and then use it from the same application. Cant think of any possibility

like image 430
Tasawer Khan Avatar asked May 18 '11 22:05

Tasawer Khan


People also ask

How Java code compiles and run?

Java source code is compiled into bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file extension . class . When the program is to be run, the bytecode is converted, using the just-in-time (JIT) compiler.

Does Java compile at runtime?

However, before execution, Java source code needs to be compiled into bytecode. Bytecode is a special machine language native to the JVM. The JVM interprets and executes this code at runtime.

How do I compile a Java code?

Open a command prompt window and go to the directory where you saved the java program. Assume it's C:\. Type 'javac MyFirstJavaProgram. java' and press enter to compile your code.


2 Answers

Check out Create dynamic applications with javax.tools. Second time I've referenced this today--I swear I don't work for them.

like image 170
karmakaze Avatar answered Sep 19 '22 07:09

karmakaze


You can use an instance of JavaCompiler:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

Follow the link for the an example on how to use it.

like image 35
iruediger Avatar answered Sep 20 '22 07:09

iruediger