[英]Groovy: AST transformation to delegate toString call to a String field
是否有注釋使Groovy將toString()
調用委派給該類的特定String字段?
@Delegate
轉換不會攔截toString()
方法調用:
@TupleConstructor
class Person {
@Delegate
String name
}
println new Person('bdkosher') // prints "Person@62aa4b4b" instead of "bdkosher"
@ToString
方法也不是我想要的,因為它位於類級別,需要指定字段名稱,並且在輸出中包括類名稱,例如
import groovy.transform.*
@ToString(includes='name')
@TupleConstructor
class Person {
String name
}
println new Person('bdkosher') // prints "Person(bdkosher)"
是否有注釋使Groovy將toString()調用委派給該類的特定String字段?
至少不使用@Delegate ,原因有兩個:
GroovyObject
接口中的方法都不適合委托 (來自@Delegate的技術說明 ) 例:
import groovy.transform.*
@TupleConstructor
class Person {
@Delegate String name
}
//Cannot delegate to name because toString() from GroovyObject
//will take precedence over the delegation to name field.
println new Person('John')
例:
import groovy.transform.*
//@ToString, @EqualsAndHashCode, @TupleConstructor implicit
@Canonical
class Person {
@Delegate String name
}
//Cannot delegate to name field because owner's (Person) toString()
//will take precedence over the delegation to name field.
println new Person('John')
我認為舊的好方法是:
import groovy.transform.*
@TupleConstructor
class Person {
String name
String toString() {
name
}
}
println new Person('John')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.