Is there an annotation to get Groovy to delegate a toString()
call to a particular String field of that class?
The @Delegate
transformation won't intercept toString()
method calls:
@TupleConstructor
class Person {
@Delegate
String name
}
println new Person('bdkosher') // prints "Person@62aa4b4b" instead of "bdkosher"
The @ToString
approach isn't quite what I'm looking for, either, as it is placed on the class level, requires the field name to be specified, and it includes the class name in the output, eg
import groovy.transform.*
@ToString(includes='name')
@TupleConstructor
class Person {
String name
}
println new Person('bdkosher') // prints "Person(bdkosher)"
Is there an annotation to get Groovy to delegate a toString() call to a particular String field of that class?
Not with @Delegate at least , because of 2 major reasons:
GroovyObject
interface are not candidates for delegation (from technical notes of @Delegate ) Example:
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')
Example:
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')
I think the good old way:
import groovy.transform.*
@TupleConstructor
class Person {
String name
String toString() {
name
}
}
println new Person('John')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.