我正在尝试在 java 中运行 groovy 脚本

我有一个已解析的 HTML 文件,其中有一个标签,里面有一个 groovy 脚本。我在字符串中有 groovy 脚本,我必须在运行时执行它并保留状态,以便以后可以使用它。

任何人都知道如何:

  1. 在java中运行groovy脚本

  2. 保留该状态以供进一步使用。

谢谢你!


湖上湖
浏览 61回答 1
1回答

POPMUISE

该类groovy.util.Eval可能是在运行时动态执行 Groovy 的最简单方法。下面给出一个示例:import groovy.util.Eval;public class Goovy123 {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Eval.me("33*3"));//99&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Eval.me("'foo'.toUpperCase()"));//FOO&nbsp; &nbsp; }}我在项目中使用了以下 Maven 依赖项来获取所需的库:<dependency>&nbsp; &nbsp; <groupId>org.codehaus.groovy</groupId>&nbsp; &nbsp; <artifactId>groovy-all</artifactId>&nbsp; &nbsp; <version>2.5.8</version>&nbsp; &nbsp; <type>pom</type></dependency>更新:我发布此更新是为了添加我原来的答案中缺少的州的示例。使用该类groovy.lang.Binding,您可以将状态保存在变量中并稍后在程序中使用它。下面给出一个示例:import groovy.lang.Binding;import groovy.lang.GroovyShell;import groovy.util.Eval;public class Goovy123 {&nbsp; &nbsp; public static void main(String[] args) throws InterruptedException {&nbsp; &nbsp; &nbsp; &nbsp; Binding binding = new Binding();&nbsp; &nbsp; &nbsp; &nbsp; String foo="foo";&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; binding.setVariable("foo", foo);&nbsp; &nbsp; &nbsp; &nbsp; GroovyShell shell = new GroovyShell(binding);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Original state: "+binding.getVariable("foo"));&nbsp; &nbsp; &nbsp; &nbsp; shell.evaluate("foo=foo.toUpperCase();");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Changed state: "+binding.getVariable("foo"));&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java