简体   繁体   中英

Groovy: AST transformation to delegate toString call to a String field

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:

  • Static methods, synthetic methods or methods from the 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')
  • All methods defined in the owner class (including static, abstract or private etc.) take precedence over methods with identical signatures from a @Delegate field

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM