gpt4 book ai didi

gradle - 将对象实例添加到 gradle 插件扩展

转载 作者:行者123 更新时间:2023-12-04 04:20:55 26 4
gpt4 key购买 nike

我有类似下面的插件,其中我有一个外部命名空间,其中有一个对象的单个“具体”实例( mother )加上另一个集合( children )。

family {
mother {
firstname = 'John'
lastname = 'Cleese'
}
children {
son {
firstName = 'John'
lastName = 'Cleese'
}
daughter {
firstName = 'Jane'
lastName = 'Cleese'
}
}
}

我能够添加集合对象并根据我见过的各种示例读取变量,但不确定如何添加具体实例。
如何在扩展对象上定义它?

显示问题的代码 - 我想添加 mother作为带有插件的单个实例。

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.*

class Person
{
final String name
String firstName
String lastName
Person(String name) { this.name = name }
}

class FamilyExtension {

final NamedDomainObjectContainer<Person> children
Person mother
Person father

FamilyExtension(children) {
this.children = children
}

def children(Closure closure) {
children.configure(closure)
}
}

class FamilyPlugin implements Plugin<Project> {

void apply(Project project) {
project.task('sayHello', type: DefaultTask) << {
println(
"Hello ${project.family.children["son"].firstName} " +
"and hello ${project.family.children["daughter"].firstName} ")
}

def children = project.container(Person)

project.extensions.create("family", FamilyExtension, children)
}
}

apply plugin: FamilyPlugin

family {
// How do I add support for this?
// mother {
// firstname = 'John'
// lastname = 'Cleese'
// }
children {
son {
firstName = 'John'
lastName = 'Cleese'
}
daughter {
firstName = 'Jane'
lastName = 'Cleese'
}
}
}

最佳答案

好吧,添加mother关闭family您将以下代码添加到 FamilyExtension类(class)

Person mother(Closure closure) {
mother = new Person()
project.configure(mother, closure)
return mother
}

如果,同时你想拥有 children在家庭一中扩展您将以下代码添加到 FamilyPlugin.apply方法

project.extensions.create("family", FamilyExtension, instantiator, project)
project.family.extensions.create("children", FamilyExtension.Children, project)

然后你添加

void son(Closure closure) {
Person son = new Person()
project.configure(son, closure)
children.add(son)
}

能够添加 son children 内关闭一。

要查看整个项目和更详细的解释,请访问 Github 项目 https://github.com/andriipanasiuk/family-gradle-plugin

关于gradle - 将对象实例添加到 gradle 插件扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28548887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com