电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

Groovy解惑——closure中的owner


发布日期:2024/7/24
 

本篇将讲解一下closure中的owner以及thisdelegate以及owner三者间的关系

先让我们来看个例子

class OwnerDemo {def outerClosure = {println the owner of outerClosure: + ownerdef innerClosure = {println the owner of innerClosure: + ownerdef innestClosure = {println the owner of innestClosure: + owner}innestClosure()}innerClosure()}}def ownerDemo = new OwnerDemo()ownerDemoouterClosure()

运行结果

the owner of outerClosure: OwnerDemo@eccfe

the owner of innerClosure: OwnerDemo$_closure@cf

the owner of innestClosure: OwnerDemo$_closure_closure@dcbb

注意OwnerDemo$_closure指的是outerClosure的类名而OwnerDemo$_closure_closure指的是innerClosure的类名

通过这个例子大家就清楚了closure的owner引用的是该closure的拥有者

那么this delegate以及owner有什么关系呢?

隐式变量delegate的默认值为owner

如果closure没有嵌套在其他closure中那么该closure的owner的值为this;

否则该closure的owner引用的是直接包含该closure的closure

让我们用事实来说话吧

class OwnerDemo {def outerClosure = {println the owner of outerClosure: + ownerprintln the delegate of outerClosure: + delegateprintln this in the outerClosure: + thisdef innerClosure = {println the owner of innerClosure: + ownerprintln the delegate of innerClosure: + delegateprintln this in the innerClosure: + thisdef innestClosure = {println the owner of innestClosure: + ownerprintln the delegate of innestClosure: + delegateprintln this in the innestClosure: + this}println innestClosure: + innestClosureinnestClosure()}println innerClosure: + innerClosureinnerClosure()}}def ownerDemo = new OwnerDemo()def outerClosure = ownerDemoouterClosureprintln outerClosure: + outerClosureouterClosure()

运行结果

outerClosure: OwnerDemo$_closure@ccb

the owner of outerClosure: OwnerDemo@ef

the delegate of outerClosure: OwnerDemo@ef

this in the outerClosure: OwnerDemo@ef

innerClosure: OwnerDemo$_closure_closure@ebdb

the owner of innerClosure: OwnerDemo$_closure@ccb

the delegate of innerClosure: OwnerDemo$_closure@ccb

this in the innerClosure: OwnerDemo@ef

innestClosure: OwnerDemo$_closure_closure_closure@aee

the owner of innestClosure: OwnerDemo$_closure_closure@ebdb

the delegate of innestClosure: OwnerDemo$_closure_closure@ebdb

this in the innestClosure: OwnerDemo@ef

大家可以从其中值的关系看出this delegate以及owner三者的关系与我们之前所说的相符:)

上一篇:利用基本数组类型搭建可自扩展的数组类

下一篇:Jar内外配置文件的读取