Running Groovy script from Gradle using GroovyShell: Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/cli/ParseException

后端 未结 2 961
终归单人心
终归单人心 2021-01-05 14:59

I want to run a groovy command-line script from my Gradle build script.

I\'m using this code in my Gradle script:

def groovyShell = new GroovyShell(         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 16:01

    Thanks to this unaccepted SO answer, I finally found what I needed to do:

    //define our own configuration
    configurations{
        addToClassLoader
    }
    //List the dependencies that our shell scripts will require in their classLoader:
    dependencies {
        addToClassLoader group: 'commons-cli', name: 'commons-cli', version: '1.2'
    }
    //Now add those dependencies to the root classLoader:
    URLClassLoader loader = GroovyObject.class.classLoader
    configurations.addToClassLoader.each {File file ->
        loader.addURL(file.toURL())
    }
    
    //And now no more exception when I run this:
    def groovyShell = new GroovyShell();
    groovyShell.run(file('script.groovy'), ['arg1', 'arg2'] as String[])
    

    You can find more details about classLoaders and why this solution works in this forum post.

    Happy scripting!

    (Before you downvote me for answering my own question, read this)

提交回复
热议问题