Grape似乎可以很好地为你的类路径添加jar.它还可以执行很多其他操作,例如提取和依赖关系管理.例如
#!/home/robert/bin/groovy
import org.apache.commons.lang.StringUtils
@Grab(group='commons-lang', module='commons-lang', version='2.4')
def strings = ['Hello', 'Groovy', 'AVeryLongWord!', 'A simple sentence']
strings.each { String aString ->
println "$aString: ${StringUtils.abbreviate(aString,10)}"
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,如果我的文件系统上有一个jar,我想动态添加到文件系统,那么我不得不求助于一个更加丑陋的解决方案.
#!/home/robert/bin/groovy
def loader = this.class.classLoader.rootLoader
loader.addURL(new File("/home/robert/somejars/arithmetic-1.1.jar").toURI().toURL())
// can't use traditional package import
arithmeticMainClass = Class.forName("org.scharp.arithmetic.Main")
println "42 - 23 = " + arithmeticMainClass.subtract(42, 23)
// can't use "new" operator
myArithmeticObject = arithmeticMainClass.newInstance()
Run Code Online (Sandbox Code Playgroud)
有没有办法让葡萄从文件系统中抓取一个罐子?如果没有,我可以以某种方式复制葡萄在groovy/java中做的事情吗?
我希望这个解决方案适用于可由许多用户和许多不兼容的jar运行的脚本,因此将jar添加到公共目录(如〜/ .groovy/lib /)将不起作用.
我可以为本地的jar库创建一个本地maven存储库,但这似乎有些过分.