It depends.... You have two options (which are close, but requires work).
You can use the "java compiler api", which allows you to compile java. So, you can use it to compile and run dynamically generated code.
Java Scripting api provide supports for third party JSR 223 implementations. Jython provides a JSR 223 implementation and hence can be executed using the JDK apis.
Jython can also execute java code, so this means the example you have given can be executed. For more information look here