简体   繁体   English

从Java源代码调用用Java编写的脚本

[英]Invoke script written in Java from Java source code

I am aware of the Java Scripting API (which runs scripts written in JavaScript, Groovy etc) and several expression languages (SpEL, JEXL, JUL). 我知道Java Scripting API(运行用JavaScript,Groovy等编写的脚本)和几种表达式语言(SpEL,JEXL,JUL)。 But it is possible to write scripts in Java itself and then invoke that script from Java code? 但是可以用Java编写脚本然后从Java代码调用该脚本吗?

I found some information on compiling Java programmatically via the tools API but this not like scripting (ie the context is different). 我找到了一些关于通过工具API以编程方式编译Java的信息,但这不像脚本(即上下文不同)。

I imagine something like this script being executed by my Java code: 我想像这个脚本由我的Java代码执行:

int i = 42 + getFoo();
setBar(i);

Now - when invoked with a context that provides getFoo and setBar methods - it should evaluate i and call the method. 现在 - 当使用提供getFoosetBar方法的上下文调用时 - 它应该计算i并调用该方法。

Try BeanShell or the Compiler API or javax.script ... 尝试使用BeanShellCompiler APIjavax.script ...

one either has to interpret the text input or compile to byte-code, somehow. 一个人要么必须解释文本输入,要么以某种方式编译成字节码。

Consider using exp4j 's nice API. 考虑使用exp4j的漂亮API。 Also check out other options at https://stackoverflow.com/a/41532702/37020 另请参阅https://stackoverflow.com/a/41532702/37020上的其他选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM