值提取系列
值提取系列
字符串值提取工具-04-java 调用 java? Janino 编译工具
代码地址
场景
我们希望通过 java 执行 groovy,如何实现呢?
入门例子
maven 依赖
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>3.0.9</version>
</dependency>
代码
package org.example;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
public class GroovyScriptExecutorMain {
public static void main(String[] args) {
// 创建绑定对象
Binding binding = new Binding();
binding.setVariable("name", "World");
// Groovy 脚本内容
String scriptContent =
"def greet(name) { " +
" return \"Hello, $name!\" " +
"}; " +
"greet(name)";
// 创建 GroovyShell 对象
GroovyShell shell = new GroovyShell(binding);
// 解析并执行脚本
Object result = shell.evaluate(scriptContent);
// 输出结果
System.out.println(result); // 输出 "Hello, World!"
}
}
网友评论