Running java code stored in a string variable created dynamically inside a java application (ie at runtime) is not straightforward in Java.
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.
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 eval function.
x=eval("1+1"); // x will got the value 2 assigned
For instance, if you want to execute the above code 1+1 with Nashorn , you will write the below java code where you can find again the eval function.
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
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)