2017-04-25 60 views
1

我有一个简约的build.gradle文件,其中包含goodbad任务。我想明白为什么这个不行,给我一个奇怪的错误:从任务引用全局变量会杀死我的gradle任务

def owner = 1 

task('bad') { 
    doLast { 
     println "My owner is, ${owner}" 
    } 
} 

task good { 
    doLast { 
     println 'This is good' 
    } 
} 

这是输出:

FAILURE: Build failed with an exception. 

* Where: 
Build file 'test\build.gradle' line: 4 

* What went wrong: 
A problem occurred evaluating root project 'test'. 
> No signature of method: build_6t4ha87o2gnjb2kllhp0wwfpi$_run_closure1.doLast() is applicable for argument types: (build_6t4ha87o2gnjb2kllhp0wwfpi$_run_closure 
1$_closure4) values: [[email protected]] 
Possible solutions: doCall(), doCall(java.lang.Object), collect(), collect(), isCase(java.lang.Object), isCase(java.lang.Object) 

* Try: 
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. 

BUILD FAILED 

但是简单地从println的去除参考owner甚至只重命名我的全球owner变量为owner1的作品。看起来我正在干扰一些gradle内部,但不完全确定如何。

我在这个实验中使用了gradle 3.4。

回答

1

如您所想,owner在内部使用。具体而言,它由Groovy类Closure使用。 您在定义为Closure的任务中,因此,当您将owner声明为def时,编译器不知道您是否参考owner变量或转换后的get方法getOwner()(将在owner中转换)。

您可以验证之前发生难度以这种方式找到(您已删除您的所有者声明之后):

task verifyOwnerExistence { 
    println "Owner exists: ${owner != null}" 
}