【问题标题】:Failing scripts in groovy using Grab使用 Grab 在 groovy 中失败的脚本
【发布时间】:2013-09-22 20:56:30
【问题描述】:

以下 groovy 脚本使用命令行失败

@Grab("org.apache.poi:poi:3.9")
println "test"

错误:

unexpected token: println @ line 2, column 1.
  println "test"
  ^
1 error

删除Grab,它的工作原理! 我错过了什么?

$>groovy -v
Groovy Version: 2.1.7 JVM: 1.7.0_25 Vendor: Oracle Corporation OS: Linux

【问题讨论】:

  • @Grab 注解仅适用于import 语句。

标签: groovy groovy-grab


【解决方案1】:

文件“Grabber.groovy”

package org.taste

import groovy.grape.Grape

//List<List[]> artifacts => [[<group>,<module>,<version>,[<Maven-URL>]],..]
static def grab (List<List[]> artifacts) {
    ClassLoader classLoader = new groovy.lang.GroovyClassLoader()
    def eal = Grape.getEnableAutoDownload()
    artifacts.each { artifact -> {
            Map param = [
                classLoader: classLoader, 
                group : artifact.get(0),
                module : artifact.get(1),
                version : artifact.get(2),
                classifier : (artifact.size() < 4) ? null : artifact.get(3)
            ]
            println param
            Grape.grab(param) 
        }
    }
    Grape.setEnableAutoDownload(eal)
}

用法:

package org.taste
import org.taste.Grabber

Grabber.grab([
    [ "org.codehaus.groovy.modules.http-builder", "http-builder", '0.7.1'],
    [ "org.postgresql", "postgresql", '42.3.1', null ],
    [ "com.oracle.database.jdbc", "ojdbc8", '12.2.0.1', null]
])

【讨论】:

    【解决方案2】:

    注释只能应用于某些目标。见SO: Why can't I do a method call after a @Grab declaration in a Groovy script?

    @Grab("org.apache.poi:poi:3.9")
    dummy = null
    println "test"
    

    您也可以将grab用作方法调用:

    import static groovy.grape.Grape.grab
    grab(group: "org.apache.poi", module: "poi", version: "3.9")
    println "test"
    

    更多信息请参考Groovy Language Documentation > Dependency management with Grape

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 2021-02-18
      • 2015-11-15
      • 2011-09-14
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多