熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Groovy解惑——closure中的owner

2022-06-13   來源: Java核心技術 

  本篇將講解一下closure中的owner以及thisdelegate以及owner三者間的關系

  先讓我們來看個例子


    class OwnerDemo {   def outerClosure = {   println the owner of outerClosure: + owner   def innerClosure = {   println the owner of innerClosure: + owner   def 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: + owner   println the delegate of outerClosure: + delegate   println this in the outerClosure: + this   def innerClosure = {   println the owner of innerClosure: + owner   println the delegate of innerClosure: + delegate   println this in the innerClosure: + this   def innestClosure = {   println the owner of innestClosure: + owner   println the delegate of innestClosure: + delegate   println this in the innestClosure: + this   }   println innestClosure: + innestClosure   innestClosure()   }   println innerClosure: + innerClosure   innerClosure()   }   }   def ownerDemo = new OwnerDemo()   def outerClosure = ownerDemoouterClosure   println outerClosure: + outerClosure   outerClosure()

  運行結果

  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三者的關系與我們之前所說的相符 :)



From:http://tw.wingwit.com/Article/program/Java/hx/201311/25968.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.