groovyjargroovy-grape

Make groovy script grab a jar off the filesystem like grape


Grape seems to work fairly well for adding jars to your classpath. It also does a lot of other things such as fetching and dependency management. e.g.

#!/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)}"
}

Unfortunately if there is a jar on my filesystem that I want to dynamically add to the filesystem then I have to resort to a much uglier solution.

#!/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()

Is there a way to make grape grab a jar from the filesystem? If not, can I somehow replicate what grape is doing in groovy/java?

I would like this solution to work for scripts that can be run by many users and many incompatible jars so adding jars to a common directory such as ~/.groovy/lib/ won't work.

I could create a local maven repository for local, jar libaries but that seems like overkill.


Solution

  • There's been some interest in adding this feature to grape but nothing serious. My guess is that it's unlikely that this will be added in the near future. (6-18 months)