Groovy与Grape和AntBuilder类加载器问题

我想用groovy做一个小ftp脚本,发现这个帖子 http://www.hhhhq.org/blog/2009/05/01/ftp-using-groovy-and-ant/
由于有几个依赖项,我想使用Grape.所有依赖项都已解析并存在于缓存中.但我无法让Ant在其他库中找到可选任务.
它总是说

Caught: : Problem: Failed to create task or type ftp
Cause: the class org.apache.tools.ant.taskdefs.optional.net.FTP was not found.
        This looks like one of Ant's optional components.
Action: Check that the appropriate optional JAR exists in
        -ANT_HOME\lib
        -the IDE Ant configuration dialogs

Do not panic,this is a common problem.
The commonest cause is a missing JAR.

This is not a bug; it is a configuration problem

        at GrabTest.runMe(GrabTest.groovy:15)
        at GrabTest.run(GrabTest.groovy:26)

Groovy版本:1.6.5 JVM:1.6.0_15

这是我的源代码

@Grab(group='ant',module='ant',version='[1.6.5,)')
@Grab(group='ant',module='ant-nodeps',version='[1.0,module='ant-apache-oro',)') 
@Grab(group='ant',module='ant-commons-net',)') 
@Grab(group='apache-oro',module='jakarta-oro',version='[2.0.8,)')
@Grab(group='commons-net',module='commons-net',version='[1.4,)')
def runMe() {
    // works
    println getClass().getClassLoader().loadClass("org.apache.tools.ant.taskdefs.optional.net.FTP")

    def ant = new AntBuilder()

    println getClass().getClassLoader() //groovy.lang.GroovyClassLoader$InnerLoader
    println ant.getClass().getClassLoader() //org.codehaus.groovy.tools.RootLoader
    ant.ftp( server:"ftp.foo.com",userid:"user",password:"passwd",passive:"yes",verbose:"yes",remotedir:"/pub/incoming",binary:"yes" ) {
                fileset( dir:"." ) { include( name:"**/*.gz" ) }
            }
}

runMe()

正如你所看到的,我怀疑是类问题的类加载器
Grape不会在那里注入依赖项.
知道如何让它工作吗?

解决方法

您是否正确怀疑类加载器是问题的根源.正如您的代码已经揭示的那样,AntBuilder是从RootLoader加载的,它无法访问@Grab注释所加载的类.正如 GROOVY-3730所示,Groovy 1.7将解决这个问题.

但是,您可以通过直接使用groovy.grape.Grape.grab(Map dependency)方法解决您的问题,您可以在其中设置应该用于加载依赖项的特定类加载器:

import groovy.grape.Grape;

Grape.grab(group:'ant',module:'ant',version:'1.6.5',classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'ant',module:'ant-nodeps',module:'ant-apache-oro',module:'ant-commons-net',classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'commons-net',module:'commons-net',version:'1.4.1',classLoader:this.class.classLoader.rootLoader)
Grape.grab(group:'oro',module:'oro',version:'2.0.8',classLoader:this.class.classLoader.rootLoader)

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...