Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic code execution

Tags:

java

Similar to dynamic SQL, wherein a String is executed as an SQL at runtime, can we have Java code run dynamically? Like I return a String which is a Java code and then I execute at runtime. Is this possible?

like image 794
Sid Avatar asked Nov 12 '10 15:11

Sid


2 Answers

For real Java code, this is possible using the JavaCompiler interface. However, it's very inconvenient to use since it's just an interface to a real Java compiler that expects to compile entire class definitions found in files.

The easiest way to execute code supplied at runtime would be to use the Rhino JavaScript engine.

Both of these options have been only in Java 6, though I believe the scripting interface existed before, so you could use Rhino in an earlier JRE if you download and add it to the classpath.

like image 194
Michael Borgwardt Avatar answered Oct 18 '22 05:10

Michael Borgwardt


Javassist

You would need to use a bytecode manipulation library such as Javassist (Wikipedia), in order to run an arbitrary string that is provided at runtime. Javassist allows you to create a CtClass based on a string representing source code; and can then turn this into compiled Class object via a particular classloader, so that the class is then available to your application. Other libraries would need to do something similar to these two steps in order to achieve the same thing.

So it is possible, but it's very heavyweight and is likely to make your application very hard to reason about. If at all possible, consider designing a very flexible class statically, and having it accept parameters that control its behaviour.

like image 31
Andrzej Doyle Avatar answered Oct 18 '22 04:10

Andrzej Doyle