当我学习 Groovy 时,最令人困惑的概念之一是:lazy property。
从 C/C++ 中找不到类似的东西
有谁知道我们为什么需要这些东西以及没有它我们如何生活,或者其他方法。
感谢任何帮助:)
最佳答案
@Lazy
groovy 中的注释通常用于创建时间或内存昂贵的对象中的字段。使用此注释,创建对象实例时不会计算对象中的字段值,而是在您第一次调用以获取它时计算。
因此,即您创建了一个对象的实例,但您没有使用 @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'
希望这可以帮助,
关于groovy - 为什么我们在 Groovy 中需要 @lazy 属性,它的优势是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24154726/