【问题标题】:Groovy: AST transformation to delegate toString call to a String fieldGroovy:将 toString 调用委托给 String 字段的 AST 转换
【发布时间】:2014-02-27 18:05:39
【问题描述】:

是否有注释让 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 delegates annotations


    【解决方案1】:

    是否有注释让 Groovy 将 toString() 调用委托给该类的特定 String 字段?

    至少不使用@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')
    
    • 在所有者类中定义的所有方法(包括静态、抽象或私有等)都优先于 @Delegate 字段中具有相同签名的方法

    例子:

    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')
    

    【讨论】:

    • 好的“ol”方式对我来说有点太“好”了,但它仍然有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多