我在Groovy中有这段代码:
class Person {
def age
Person () {
println age // null
}
}
def p = new Person ([age: '29'])
println p.age // 29
我需要在构造函数中读取年龄值,但它尚未设置。
我该怎么做?
注意:我不想使用init()方法并且每次都手动调用,比如
class Person {
def age
def init() {
println age // now have 29
}
}
def p = new Person ([age: '29'])
p.init()
println p.age // 29
链接到GroovyConsole。
谢谢!
答案 0 :(得分:7)
您可以编写如下构造函数:
class Person {
def age
Person(Map map) {
for (entry in map) {
this."${entry.key}" = entry.value
}
println age
}
}
如果您正在使用groovy 1.8,请查看@TupleConstructor
注释,它将自动构建一个类似上面的构造函数,以及基于列表的构造函数。
import groovy.transform.TupleConstructor
@TupleConstructor
class Person {
int age
}
p = new Person([age: 99])
assert p.age == 99