Executing dynamic Java code over JSR-223

折月煮酒 提交于 2020-01-04 05:43:24

问题


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<ScriptEngineFactory> 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?


回答1:


I am a bit late for this thread, but I just released version 1.1.0 of the jshell-scriptengine.

Have at look at: https://github.com/eobermuhlner/jshell-scriptengine




回答2:


Check out the SciJava Java Scripting plugin

Docs are a bit thin. See the Maven Repository and note that the resolver is the ImageJ Releases repository (http://maven.imagej.net/content/repositories/releases/)




回答3:


Have you seen JShell tool and API in #java9? It is not JSR-223 based - nevertheless a Java API (and a command line tool) that uses Java as a "scripting language".



来源:https://stackoverflow.com/questions/45037984/executing-dynamic-java-code-over-jsr-223

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!