Starting with Java 6, you can compile and run the Java compilation unit, defined as String or File, using the standard APIs in the SDK (the compilation unit is basically everything that comes in the package .java package, import, classes / interfaces / enums ), look at an example . However, you cannot run an arbitrary Java fragment similar to the one asked in your question.
If at all possible, it would be better to introduce another scripting language that allows you to run code snippets from a Java program - for example, JavaScript, Groovy, MVEL , BeanShell , etc.
source share