美文网首页
字符串值提取工具-03-java 调用 groovy

字符串值提取工具-03-java 调用 groovy

作者: 老马啸西风2020 | 来源:发表于2024-08-13 11:01 被阅读0次

值提取系列

值提取系列

字符串值提取工具-01-概览

字符串值提取工具-02-java 调用 js

字符串值提取工具-03-java 调用 groovy

字符串值提取工具-04-java 调用 java? Janino 编译工具

字符串值提取工具-05-java 调用 shell

字符串值提取工具-06-java 调用 python

字符串值提取工具-07-java 调用 go

代码地址

value-extraction 值提取核心

场景

我们希望通过 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!"
    }

}

相关文章

网友评论

      本文标题:字符串值提取工具-03-java 调用 groovy

      本文链接:https://www.haomeiwen.com/subject/jufjkjtx.html