groovy:@Lazy注释在特质中不起作用

时间:2016-02-21 14:03:27

标签: groovy traits lazy-initialization

我试图在特征中使用@Lazy注释(http://docs.groovy-lang.org/docs/next/html/documentation/#xform-Lazy)来仅在使用时初始化对象。

trait MyTrait{
  @Lazy String test = {
    new Exception().printStackTrace()
    return 'test'
  }()
}

无论是否使用,都会创建对象。我在初始化闭包中添加了一个printStackTrace,以确保我不会无意中调用该变量。在实例化实现特征的类时,将创建对象。

1 个答案:

答案 0 :(得分:1)

这似乎是一个错误。 @Lazy在特质中不起作用。您应该使用Groovy创建一个问题单,以便更正此问题。

为了证明这个问题,我已经扩展了你的代码来创建一个测试(作为一个简单的groovy脚本运行),它显示@Lazy适用于Class,但在用于a trait时失败了 class MyBase{ @Lazy String test = { 'test' }() } class TestBaseClass extends MyBase{} def tb = new TestBaseClass(); //Dump the current state to output an assert test hasn't been initialized println "Testing @Lazy on a Class.." println tb.dump() assert tb.dump().contains('test=null') //FOR A CLASS, THIS WILL SUCCEED //Access the test property causing initialization println "Accessing the test property." assert tb.test //Dump the current state to output an assert test has now been initialized println tb.dump() assert tb.test == 'test' trait MyTrait{ @Lazy String test = { 'test' }() } class TestClass implements MyTrait{} def t = new TestClass(); //Dump the current state to output an assert test hasn't been initialized println "\nTesting @Lazy on a Trait.." println t.dump() assert t.dump().contains('test=null') //FOR A TRAIT, THIS WILL FAIL THE ASSERTION - A BUG? //Access the test property causing initialization println "Accessing the test property." assert t.test //Dump the current state to output an assert test has now been initialized println t.dump() assert t.test == 'test'

reduce