以下 groovy 语法的真正含义是什么?
Gradle 文档宣传了 build.gradle 是如何只是 groovy 的。 Android 团队已将默认的 build.gradle 简化到它看起来不像代码(至少对我来说)。请用常规语法解释一下这是做什么的。例如,这些全局变量声明是Android插件使用的吗?
如果您引用http://groovy-lang.org/syntax.html,则可获得奖励积分作为您解释的一部分。
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.crittercism"
minSdkVersion 15
targetSdkVersion 21
versionCode 5
versionName "5.0"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
最佳答案
您可以将 gradle 构建脚本视为一些代码,委托(delegate)给一个对象,该对象可以响应其中编写的方法调用。
该脚本使用了大量 Groovy 语法糖,因此删除它们,它应该如下所示:
apply( [plugin: 'com.android.application'] );
android({
compileSdkVersion( 21 );
buildToolsVersion( "21.1.2" );
defaultConfig({
applicationId( "com.crittercism" );
minSdkVersion( 15 );
targetSdkVersion( 21 );
versionCode( 5 );
versionName( "5.0" );
});
});
dependencies({
compile( fileTree([dir: 'libs', include: ['*.jar']]) );
});
所以脚本实际上是一堆方法调用:
def apply( map )
def android(闭包)
def 依赖项(闭包)
这个android(Closure)
将接收一个闭包,并将其中调用的方法委托(delegate)给一个可以响应这些方法的对象:
defcompileSdkVersion(Integer)
def buildToolsVersion(String)
...
鉴于此,我们可以解析脚本,将其委托(delegate)给某个对象,然后执行它。
使用DelegatingBaseScript
进行委托(delegate)是一种方法(不确定 Gradle 是否这样做)。这是一个简化的工作版本:
import org.codehaus.groovy.control.CompilerConfiguration
gradleScript = '''
apply plugin: 'com.android.application'
android({
compileSdkVersion( 21 )
buildToolsVersion( "21.1.2" )
})'''
class PocketGradle {
def config = [apply:[]].withDefault { [:] }
def apply(map) {
config.apply << map.plugin
}
def android(Closure closure) {
closure.delegate = new Expando(
compileSdkVersion: { Integer version ->
config.android.compileSdkVersion = version
},
buildToolsVersion : { String version ->
config.android.buildToolsVersion = version
},
)
closure()
}
}
def compiler = new CompilerConfiguration(scriptBaseClass: DelegatingScript.class.name)
shell = new GroovyShell(this.class.classLoader, new Binding(), compiler)
script = shell.parse gradleScript
script.setDelegate( gradle = new PocketGradle() )
script.run()
assert gradle.config == [
apply: ['com.android.application'],
android: [
compileSdkVersion: 21,
buildToolsVersion: '21.1.2'
]
]
您可以执行Groovy Web Console
中的脚本(单击“在控制台中编辑”,然后单击“执行脚本”)。
大部分语法解释都在 DSL section 中:
- Command chains
Groovy lets you omit parentheses around the arguments of a method call for top-level statements. "command chain" feature extends this by allowing us to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls.
还有 Groovy ConfigSlurper
,但我不确定它是否能达到 Gradle 想要的程度。
关于groovy - 请解释一下Android build.gradle groovy语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29463706/