一招教你使用Java執(zhí)行g(shù)roovy腳本的兩種方式
介紹
記錄 Java 執(zhí)行 groovy 腳本的兩種
一種是通過(guò)腳本引擎 ScriptEngine 提供的 eval(String) 方法執(zhí)行腳本內(nèi)容;一種是執(zhí)行 groovy 腳本;
二者都通過(guò) Invocable 來(lái)傳遞參數(shù)并獲取執(zhí)行結(jié)果;
Invocable:腳本引擎的解釋器接口,提供 invokeFunction 和 invokeMethod 兩種傳遞參數(shù)并獲取執(zhí)行結(jié)果的方法,Java JDK API文檔解釋如下:

invokeFunction:

invokeMethod:

以下為案例:
引入依賴(lài)
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>1.2.74</version> </dependency>
定義腳本內(nèi)容并執(zhí)行
public void testByFunction(){
// 初始化Bindings
Bindings bindings = engine.createBindings();
// 綁定參數(shù)
bindings.put("date", new Date());
final String name = "groovy";
// 定義groovy腳本中執(zhí)行方法的名稱(chēng)
final String scriptName = "execute";
// 定義groovy腳本內(nèi)容
final String scriptContent = "def " + scriptName +"(name){" +
" println(\"now dateTime is: ${date.getTime()}\");" +
" println(\"my name is $name\");" +
" return date.getTime() > 0;" +
"}";
try {
// 執(zhí)行腳本
engine.eval(scriptContent, bindings);
// 獲取執(zhí)行結(jié)果
Invocable invocable = (Invocable) engine;
Boolean flag = (Boolean) invocable.invokeFunction(scriptName, name);
System.out.println("---------------------------------------");
System.out.println("result is: " + flag);
} catch (ScriptException | NoSuchMethodException e) {
e.printStackTrace();
}
}運(yùn)行結(jié)果:

invokeFunction方法的第一個(gè)參數(shù)為腳本的函數(shù)名稱(chēng),把scriptName拎出來(lái)通過(guò)創(chuàng)建String對(duì)象再賦值進(jìn)去,方便你看懂函數(shù)名稱(chēng)到底是哪個(gè);scriptContent中${date.getTime()}與$name的意思一樣,grovvy中的字符串可以識(shí)別${}和$占位符;bindings綁定參數(shù)與invokeFunction方法的第二個(gè)參數(shù)的區(qū)別是,前者是腳本內(nèi)全局的,而后者是定義在函數(shù)內(nèi)的;
例如把腳本內(nèi)容定義為這樣:

執(zhí)行結(jié)果就是這樣了:

實(shí)例化腳本對(duì)象并執(zhí)行
public void testByMethod(){
try {
// 初始化groovy腳本對(duì)象
final TestGroovy testGroovy = new TestGroovy();
// 定義groovy腳本中執(zhí)行方法的名稱(chēng)
final String scriptName = "execute";
// 定義參數(shù)
final Date arg_1 = new Date();
final String arg_2 = "groovy";
// 執(zhí)行腳本并獲取結(jié)果
Invocable invocable = (Invocable) engine;
Boolean flag = (Boolean) invocable.invokeMethod(testGroovy, scriptName, arg_1, arg_2);
System.out.println("---------------------------------------");
System.out.println("result is: " + flag);
} catch (ScriptException |NoSuchMethodException e) {
e.printStackTrace();
}
}TestGroovy.groovy腳本內(nèi)容:
package com.dandelion.groovy
class TestGroovy {
static def execute(Date date, String name){
println("now dateTime is: ${date.getTime()}");
println("my name is $name");
return date.getTime() < 0;
}
}運(yùn)行結(jié)果:

invokeMethod 方法的第一個(gè)參數(shù)是腳本對(duì)象,第二個(gè)參數(shù)是腳本中的函數(shù)名稱(chēng),之后為綁定的參數(shù);
源碼:
package com.dandelion.test;
import com.dandelion.groovy.TestGroovy;
import javax.script.*;
import java.util.Date;
/**
* ================================
* 測(cè)試groovy腳本的執(zhí)行方式
* @Author Him
* @Date 2021-04-21
* @Time 01:12
* ================================
*/
public class TestScriptEngine {
// 查找并創(chuàng)建指定腳本引擎
private ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
public void testByFunction(){
// 初始化Bindings
Bindings bindings = engine.createBindings();
// 綁定參數(shù)
bindings.put("date", new Date());
// 定義groovy腳本中執(zhí)行方法的名稱(chēng)
final String scriptName = "execute";
// 定義groovy腳本內(nèi)容
final String scriptContent = "def " + scriptName +"(){" +
" println(\"now dateTime is: ${date.getTime()}\");" +
" return date.getTime() > 0;" +
"}";
try {
// 執(zhí)行腳本
engine.eval(scriptContent, bindings);
// 獲取執(zhí)行結(jié)果
Invocable invocable = (Invocable) engine;
Boolean flag = (Boolean) invocable.invokeFunction(scriptName);
System.out.println("---------------------------------------");
System.out.println("result is: " + flag);
} catch (ScriptException | NoSuchMethodException e) {
e.printStackTrace();
}
}
public void testByMethod(){
try {
// 初始化groovy腳本對(duì)象
final TestGroovy testGroovy = new TestGroovy();
// 定義groovy腳本中執(zhí)行方法的名稱(chēng)
final String scriptName = "execute";
// 定義參數(shù)
final Date arg_1 = new Date();
final String arg_2 = "groovy";
// 執(zhí)行腳本并獲取結(jié)果
Invocable invocable = (Invocable) engine;
Boolean flag = (Boolean) invocable.invokeMethod(testGroovy, scriptName, arg_1, arg_2);
System.out.println("---------------------------------------");
System.out.println("result is: " + flag);
} catch (ScriptException |NoSuchMethodException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TestScriptEngine engine = new TestScriptEngine();
engine.testByFunction();
}
}到此這篇關(guān)于一招教你使用Java執(zhí)行g(shù)roovy腳本的兩種方式的文章就介紹到這了,更多相關(guān)Java執(zhí)行g(shù)roovy腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java去除中文括號(hào)小括號(hào),或者英文括號(hào)的實(shí)例代碼
這篇文章主要介紹了java去除中文括號(hào)小括號(hào),或者英文括號(hào)的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
mybatis-plus使用@EnumValue處理枚舉類(lèi)型的示例代碼
這篇文章主要介紹了mybatis-plus使用@EnumValue處理枚舉類(lèi)型的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
基于SpringBoot實(shí)現(xiàn)分布式鎖的三種方法
這篇文章主要為大家詳細(xì)介紹了基于SpringBoot實(shí)現(xiàn)分布式鎖的三種方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-12-12
Spring?Boot?3.x?開(kāi)發(fā)中緩存分區(qū)策略導(dǎo)致的數(shù)據(jù)傾斜問(wèn)題及解決方案
本文將深入剖析緩存分區(qū)導(dǎo)致數(shù)據(jù)傾斜的成因,并提供在?Spring?Boot?3.x?環(huán)境下的系統(tǒng)性解決方案,感興趣的朋友跟隨小編一起看看吧2026-04-04
詳細(xì)總結(jié)各種排序算法(Java實(shí)現(xiàn))
下面小編就為大家?guī)?lái)一篇詳細(xì)總結(jié)各種排序算法(Java實(shí)現(xiàn))。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09
部署在linux上的java服務(wù)老是掛掉問(wèn)題排查日志
當(dāng)服務(wù)器掛掉時(shí),操作系統(tǒng)通常會(huì)記錄一些異常信息,檢查服務(wù)器的系統(tǒng)日志可以幫助定位問(wèn)題所在,這篇文章主要介紹了部署在linux上的java服務(wù)老是掛掉問(wèn)題排查日志的相關(guān)資料,需要的朋友可以參考下2025-10-10
解決程序啟動(dòng)報(bào)錯(cuò)org.springframework.context.ApplicationContextExcept
文章描述了一個(gè)Spring Boot項(xiàng)目在不同環(huán)境下啟動(dòng)時(shí)出現(xiàn)差異的問(wèn)題,通過(guò)分析報(bào)錯(cuò)信息,發(fā)現(xiàn)是由于導(dǎo)入`spring-boot-starter-tomcat`依賴(lài)時(shí)定義的scope導(dǎo)致的配置問(wèn)題,調(diào)整依賴(lài)導(dǎo)入配置后,解決了啟動(dòng)錯(cuò)誤2024-11-11

