Groovy中导入外部Jar类及共享Groovy脚本方法的实现咨询
没问题,这两个场景我都给你梳理清楚~
一、Groovy中完全可以导入Jar共享库的类并使用方法
当然可行!Groovy本身和Java完全兼容,不管你的Jar里是Java类还是Groovy类,都能正常导入调用,步骤也很清晰:
第一步:确保Jar在Classpath中
- 如果是本地运行Groovy脚本,直接在执行命令时指定Classpath:
groovy -classpath /path/to/your/shared-library.jar currentScript.groovy - 如果是Maven项目,直接在
pom.xml里添加这个Jar的依赖(如果是发布到Maven仓库的共享库):<dependency> <groupId>你的库GroupId</groupId> <artifactId>你的库ArtifactId</artifactId> <version>版本号</version> </dependency>
- 如果是本地运行Groovy脚本,直接在执行命令时指定Classpath:
第二步:在Groovy脚本中正常导入并使用
和Java的导入方式完全一样,比如你的Jar里有com.example.utils.BusinessTool类:import com.example.utils.BusinessTool // 创建实例并调用方法 def tool = new BusinessTool() tool.processData("test input")
二、在currentScript.groovy中导入CommonScript.groovy的通用代码(结合Maven共享库)
如果是想复用Groovy脚本里的代码,分两种规范的处理方式,结合Maven共享库的场景给你说明:
方式1:把CommonScript改成Groovy类(推荐,适合Maven共享)
脚本形式的代码复用起来不够规范,更适合的方式是把通用代码封装成Groovy类,比如将CommonScript.groovy改成:
package com.example.common class CommonUtils { // 静态方法,直接调用 static void printLog(String message) { println "[LOG] ${message}" } // 实例方法,需要创建对象调用 String formatData(String rawData) { rawData.trim().toUpperCase() } }
然后把这个类打包进Maven共享库的Jar,之后在currentScript.groovy里直接导入使用:
import com.example.common.CommonUtils // 调用静态方法 CommonUtils.printLog("开始执行脚本") // 创建实例调用实例方法 def utils = new CommonUtils() def formatted = utils.formatData(" hello world ") println formatted
方式2:直接复用Groovy脚本文件
如果确实需要保留脚本形式,只要把CommonScript.groovy放在Maven共享库的src/main/resources目录下(打包后会在Jar的资源路径中),就可以在currentScript.groovy里通过类加载器加载并执行:
// 从Classpath中加载CommonScript.groovy def scriptResource = getClass().classLoader.getResource('CommonScript.groovy') if (scriptResource) { // 执行脚本,脚本里的方法和变量会被注入到当前脚本中 evaluate(new File(scriptResource.toURI())) // 直接调用CommonScript里定义的方法 commonProcessMethod() } else { println "找不到CommonScript.groovy资源" }
注意:这种方式下,脚本里的所有变量和方法都会成为当前脚本的一部分,要注意避免命名冲突。
内容的提问来源于stack exchange,提问作者Pavan Yalamanchili
相关产品推荐
相关产品推荐

