[英]Nested extensions in Gradle plugin
我正在尝试在我的 gradle 插件中实现以下配置
music {
artist {
artistName = "artist1"
album {
albumName = "album1"
}
}
artist {
artistName = "artist2"
album {
albumName = "album1"
}
album {
albumName = "album1"
}
}
}
这就是我到目前为止所拥有的
open class MusicPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.extensions.create("music", MusicPluginExtension::class.java)
}
}
open class MusicPluginExtension @Inject constructor(val objectFactory: ObjectFactory) {
val artists = objectFactory.domainObjectSet(Artist::class.java)
fun artist(action: Action<in Artist>) {
val artist = Artist(objectFactory)
action.execute(artist)
artists.add(artist)
}
}
open class Artist @Inject constructor(objectFactory: ObjectFactory) {
var artistName: String? = null
val albums = objectFactory.domainObjectSet(Album::class.java)
fun album(action: Action<in Album>) {
val album = Album()
action.execute(album)
albums.add(album)
}
}
open class Album() {
var albumName: String? = null
}
当我将插件应用于项目时,我能够创建闭包,但是当我尝试为Album
设置属性时失败(例如设置专辑的名称)。 这是我得到的错误:
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/user/git/pluginTest/build.gradle' line: 19
* What went wrong:
A problem occurred evaluating root project 'pluginTest'.
> Could not set unknown property 'albumName' for object of type com.plugin.Artist.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
CONFIGURE FAILED in 84ms
对此的任何帮助将不胜感激。
也许您可以使用 Gradle 的NamedDomainObjectContainer 。
interface MusicPluginExtension {
// https://docs.gradle.org/current/userguide/custom_gradle_types.html#nameddomainobjectcontainer
NamedDomainObjectContainer<Artist> getArtists()
interface Artist {
String getName()
NamedDomainObjectContainer<Album> getAlbums()
interface Album {
String getName()
}
}
}
music {
artists {
register("artist1") {
albums {
register("album1"){}
register("album2"){}
}
}
register("artist2") {
// ...
}
}
}
它适用于 1 级嵌套列表,也许它也适用于 2 级列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.