开发者

Groovy: Is there a constructor called after the copy of parameters?

I have this code in Groovy:

class Person {
    def age
    Person () {
        println age // null
    }
}

def p = new Person ([age: '29'])
println p.age // 29

I need to read age value in constructor, but it isn't setted yet.

How can I do this?

Note: I don't wan开发者_如何学Ct to use a init() method and call manually every time, like

class Person {
    def age
    def init() {
        println age // now have 29
    }
}

def p = new Person ([age: '29'])
p.init()
println p.age // 29

Link to GroovyConsole.

Thanks!


You can write a constructor like this:

class Person {
    def age

    Person(Map map) {
        for (entry in map) {
            this."${entry.key}" = entry.value
        }
        println age
    }
}

If you're using groovy 1.8, take a look at the @TupleConstructor annotation, which will automatically build a constructor like the one above, as well as a list based one.

import groovy.transform.TupleConstructor

@TupleConstructor
class Person {
    int age
}

p = new Person([age: 99])
assert p.age == 99
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜