簡體   English   中英

Groovy:AST轉換將toString委托給String字段

[英]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 ,原因有兩個:

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM