是否有注释可以让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)"
答案 0 :(得分:4)
是否有一个注释可以让Groovy将toString()调用委托给该类的特定String字段?
至少不是@Delegate ,原因有两个:
GroovyObject
界面中的静态方法,合成方法或方法不适合委派(来自technical notes of @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')