I have been executing dynamic code in my application over JSR-223 for a while now. The basics logic is:
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(engineName);
final CompiledScript compiled = ((Compilable) scriptEngine).compile(script);
Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("key", value);
compiled.eval(bindings);
This works great for Nashorn and Groovy scripting engines. However it would be great if extending the logic of the application would not require knowing the syntax and tricks of another language - the base code is in Java after all.
When listing the built-in engines there do not seem to be any present for Java:
ScriptEngineManager manager = new ScriptEngineManager();
List factoryList = manager.getEngineFactories();
for (ScriptEngineFactory factory : factoryList) {
log.debug(factory.getLanguageName());
}
I have found a few dynamic Java libraries but they do not seem to be maintained any more. I guess it is possible to write something together using the javax.tools.JavaCompiler but I am hoping that maybe I am missing something basic and there are working options for such a thing already in existence. I am also aware of the basics about jshell coming in Java 9 but I have not heard anything about it allowing code execution using the ScriptEngineManager.
How should I go about implementing scripting using the Java language itself? Are there any options beyond starting to implement my own javax.script.ScriptEngine with the help of javax.tools.JavaCompiler?
解决方案
I am a bit late for this thread, but I just released version 1.1.0 of the jshell-scriptengine.