WeBlog - Dynamic Java Code Execution
Table of Contents
1 - About
java code stored in a string variable created dynamically inside a
java application (ie at runtime) is not straightforward in Java.
2 - Sections
2.1 - Why would you need it ?
There is for sure several cases and in this section, I highlight one.
During documentation creation, you show generally a code sample and its result.
Example: the below Java code
As you can see, the documentation define a unit test.
The code being what should be performed and the result what is expected.
To implement this kind of unit test framework, you need to extract the code and to execute it before comparing it to the expected result. That's one
business case for Java dynamic execution.
Let's see now why it's not straightforward to implement it in Java.
2.2 - Why running generated Java code at runtime in Java is not straightforward ?
This kind of language have one big advantage which is that they have a structure which means that every piece of code has:
This is then possible:
- to parse it (and create a tree representation)
- to see the flow of data
- to detect fault before compile time
- to refactor it
The function that permits to do that is called generally the
x=eval("1+1"); // x will got the value 2 assigned console.log(x);
For instance, if you want to execute the above code
Nashorn , you will write the below java code where you can find again the
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); engine.eval("1+1");
This code is still
Java code. The next section will show you how to execute Java code in Java.
2.3 - Executing dynamic java code inside Java
To execute Java code, you need to:
- create dynamically your java source code
- compile it to a class,
- to load the class,
- to use the reflexion Api to discover your method and to execute it.
All this steps are explained in this article: How you can execute a string representing java code inside Java: Java - Dynamic Java code execution (at runtime)