Groovy将参数复制到Groovy类中的属性的方法是什么?

Groovy将参数复制到Groovy类中的属性的方法是什么?,groovy,constructor,Groovy,Constructor,给定一个具有属性和构造函数的对象,我希望将构造函数参数复制到属性中,然后在构造函数中做一些额外的工作 import groovy.transform.TupleConstructor @TupleConstructor class Thing{ def one def two public Thing(one, two){ doSomething() } def doSomething(){ println "doing

给定一个具有属性和构造函数的对象,我希望将构造函数参数复制到属性中,然后在构造函数中做一些额外的工作

import groovy.transform.TupleConstructor

@TupleConstructor
class Thing{
    def one
    def two

    public Thing(one, two){
       doSomething()
    }

    def doSomething(){
        println "doing something with one : $one and two: $two"
    }
}


println new Thing(1, 2).dump()
如果我在构造函数中不做任何其他操作,这将成功地将参数复制到属性,但是如果我在构造函数中调用“doSomething()”,则不会复制属性


我正在寻找将参数复制到属性的“Groovy”方法。

如果使用
TupleConstructor
,如果定义了自己的构造函数,它将不会运行

import groovy.transform.TupleConstructor

@TupleConstructor
class Thing{
    def one
    def two

    public Thing(one, two){
       doSomething()
    }

    def doSomething(){
        println "doing something with one : $one and two: $two"
    }
}


println new Thing(1, 2).dump()
正如您已经定义了一个重复的构造函数,它是
TupleConstructor
将在字节码中生成的构造函数,即使执行
@TupleConstructor(force=true)
也不会有帮助,因为您只会得到一个
java.lang.ClassFormatError:类文件中重复的方法名和签名

目前我能想到的最好办法是:

class Thing{
    def one
    def two

    public Thing( Map params ){
       this.class.declaredFields.grep { !it.synthetic }.name.each { name ->
         this[ name ] = params[ name ]
       }
       doSomething()
    }

    def doSomething(){
        println "doing something with one : $one and two: $two"
    }
}


println new Thing(one:1, two:2).dump()
尽管我在tim_yates中遗漏了一种更好的方法,但如果定义了另一个构造函数(可以归咎于code=p),TupleConstructor AST转换将不会起任何作用。如果在构建对象时需要运行其他代码,可以在静态工厂方法中添加该代码,并直接使用该代码而不是元组构造函数:

import groovy.transform.TupleConstructor

@TupleConstructor
class Thing {
    def one
    def two

    def doSomething(){
        println "doing something with one : $one and two: $two"
    }

    static create(...args) {
        def thing = new Thing(*args)
        thing.doSomething()
        thing
    }
}


println Thing.create(1, 2).dump()
请注意,我使用变量参数静态方法接收任意数量的参数,然后使用这些参数调用元组构造函数(为此使用了“spread”(
*
)操作符)


不幸的是,TupleConstructor AST转换似乎没有将元组构造函数添加为private的选项,这在本例中很有用。

另请参见,它们与此非常相似……如果东西扩展了某些内容,这也将不起作用,因为它将看不到继承的属性