我是新来的。因此,请直截了当。我要实现以下块。请注意,这些库是动态的,可供其他开发人员添加所需的库。
libraries {
slf4j 'org.slf4j:slf4j-api:1.7.21'
junit 'junit:junit:4.12'
}
这样我就可以这样叫他们了。
dependencies {
compile libraries.slf4j
testCompile libraries.junit
}
我不确定如何做到。但是我从here找到了一些相关的解决方案。如下所示:
apply plugin: GreetingPlugin
greeting {
message 'Hi'
greeter 'Gradle'
}
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
project.extensions.create("greeting", GreetingPluginExtension)
project.task('hello') {
doLast {
println "${project.greeting.message} from ${project.greeting.greeter}"
}
}
}
}
class GreetingPluginExtension {
String message
String greeter
}
问题是当我添加到
greeting
块时,我也需要在GreetingPluginExtension
中声明它们。任何想法如何使其仅在greeting
块上更新?
最佳答案
您需要做的是利用常规的元编程。您可以在下面找到一个示例,但是功能齐全。
apply plugin: LibrariesPlugin
libraries {
slf4j 'org.slf4j:slf4j-api:1.7.21'
junit 'junit:junit:4.12'
}
class LibrariesPlugin implements Plugin<Project> {
void apply(Project project) {
project.extensions.create("libraries", LibrariesPluginExtension)
project.task('printLib') {
doLast {
println "$project.libraries.slf4j"
println "$project.libraries.junit"
project.libraries.each {
println "$it.key -> $it.value"
}
}
}
}
}
class LibrariesPluginExtension {
Map libraries = [:]
def methodMissing(String name, args) {
// TODO you need to do some arg checking here
libraries[name] = args[0]
}
def propertyMissing(String name) {
// TODO same here
libraries[name]
}
Iterator iterator() {
libraries.iterator()
}
}
关于gradle - 如何在Gradle中实现此 'dynamic block'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40743415/