如果我有这样的类(class):
class Person {
def name
def greeting = "hello $name"
}
然后我打电话 鲍勃=新人(名称:“鲍勃”)
当我此时检查鲍勃时,我发现问候语中没有“鲍勃”。我做错了什么?
最佳答案
您可以use the @Lazy
annotation解决这个问题
class Person {
def name
@Lazy def greeting = "hello $name"
}
bob = new Person(name: "bob")
println bob.greeting
将根据您的需要打印hello bob
。该注释更改了问候语的 getter,以便仅在第一次调用时生成(然后缓存结果)。这具有副作用,一旦调用一次,就会使 greeting
变为静态,但您没有说明是否需要随着时间的推移而更改(由于 name
更改) ...即;
bob = new Person(name: "bob")
println bob.greeting
bob.name = 'dave'
println bob.greeting
将打印:
hello bob
hello bob
关于Groovy:构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729565/