Groovy:构造函数问题

标签 groovy

如果我有这样的类(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/

相关文章:

jenkins - 从另一个 Jenkins 管道构建时将默认 bool 参数值从 false 覆盖为 true

groovy - Jira 工作流脚本验证器的返回码

hibernate - 我们可以在 grails 中实现表拆分/在日期字段中使用基于月份的 Hibernate

android - Gradle buildType/productFlavor 使用意外的 buildConfigField

java - GGTS 格罗维 :Can't have an abstract method in a non-abstract class in DslBuilder

Java/Groovy 如何正确比较两个字符串值? .equals() 不工作

使用 namespace 进行 Groovy Xml 解析

grails - "Error Compilation error: encoded string too long:"构建时

servlets - Groovy - 如何延迟 Groovlet 修改重新编译检查

grails - 种子种子插件的种子文件中如何循环播放?