[英]Groovy MarkupBuilder name conflict
我有這個代碼:
String buildCatalog(Catalog catalog) {
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.catalog(xmlns:'http://www.sybrium.com/XMLSchema/NodeCatalog') {
'identity'() {
groupId(catalog.groupId)
artifactId(catalog.artifactId)
version(catalog.version)
}
}
return writer.toString();
}
它產生這個xml:
<catalog xmlns='http://www.sybrium.com/XMLSchema/NodeCatalog'>
<groupId>sample.group</groupId>
<artifactId>sample-artifact</artifactId>
<version>1.0.0</version>
</catalog>
請注意,“身份”標簽丟失了...我已經嘗試了世界上的所有內容來顯示該節點。 我正在撕開我的頭發!
提前致謝。
可能有更好的方法,但一個技巧是直接調用invokeMethod
:
String buildCatalog(Catalog catalog) {
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.catalog(xmlns:'http://www.sybrium.com/XMLSchema/NodeCatalog') {
delegate.invokeMethod('identity', [{
groupId(catalog.groupId)
artifactId(catalog.artifactId)
version(catalog.version)
}])
}
return writer.toString();
}
這實際上是Groovy在幕后所做的事情。 我無法讓delegate.identity
或owner.identity
工作,這是常用的技巧。
編輯 :我弄清楚發生了什么。
Groovy為每個對象添加了一個帶有identity(Closure c)
簽名identity(Closure c)
方法。
這意味着當您嘗試動態調用XML構建器上的identity
元素時,在傳入單個閉包參數時,它調用了identity()
方法,就像在外部閉包上調用delegate({...})
。
使用invokeMethod
技巧強制Groovy繞過元對象協議並將該方法視為動態方法,即使MetaObject上已存在identity
方法。
了解這一點,我們可以將更好,更清晰的解決方案整合在一起。 我們所要做的就是更改方法的簽名,如下所示:
String buildCatalog(Catalog catalog) {
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.catalog(xmlns:'http://www.sybrium.com/XMLSchema/NodeCatalog') {
// NOTE: LEAVE the empty map here to prevent calling the identity method!
identity([:]) {
groupId(catalog.groupId)
artifactId(catalog.artifactId)
version(catalog.version)
}
}
return writer.toString();
}
這更具可讀性,意圖更清晰,評論應該(希望)阻止任何人刪除“不必要的”空地圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.