为什么我们在Groovy中需要@lazy属性,它的优点是什么?

Shu*_*aru 5 groovy properties lazy-evaluation

我学习Groovy时最令人困惑的概念之一是:懒惰的属性.从C/C++中找不到类似的东西有谁知道为什么我们需要这些东西以及如何在没有它的情况下生活,或者替代方法.感谢任何帮助:)

alb*_*iff 7

@Lazygroovy中的注释通常用于对象内的一个字段,这个字段的时间或内存都很昂贵.使用此注释时,在创建对象实例时不会计算对象中的字段值,而是在第一次调用时计算它.

因此,即您创建了一个对象的实例,但是您没有获得带@Lazy注释的字段,因此永远不会计算字段值,因此您可以节省执行时间和内存资源.查看代码示例(示例有废话,但我希望有助于理解解释):

// without lazy annotation with this code token.length is calculated even
// is not used
class sample{
    String token
    Integer tokenSize = { token?.length() }()
}

def obj = new sample()
obj.token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa'

// with Lazy annotation tokenSize is not calculated because the code
// is not getting the field.
class sample{
    String token
    @Lazy tokenSize = { token?.length() }()
}

def obj = new sample()
obj.token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa'
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助,