簡體   English   中英

將閉包應用於groovy中的任意對象

[英]apply closure to an arbitrary object in groovy

在gradle中,您可以在某些地方以構建器樣式將閉包傳遞給對象本身,如下所示:

// ant is a property. an object.
ant {
    // do funky builder stuff
}

如何創建自己的自定義代碼以將閉包應用於對象? 有沒有我需要重寫的方法來支持這一點?

您可以覆蓋call運算符。 Groovy允許您不要在閉包參數周圍放置圓括號。

class A {
  def call(Closure cl) {
    print(cl())
  }
}
def a = new A();
a {
    "hello"
}

打印你好。

添加到海鷗提到的方式:

使用采取閉包的方法:

class MyClass { 
  def ant (c) {
    c.call()
  }
}

def m = new MyClass()
m.ant { 
  println "hello"
}

另一種方法是使用缺少的方法,這在采用閉包的方法名稱方面具有更大的靈活性(在您的情況下為ant ):

class A {
     def methodMissing(String name, args) {
        if (name == "ant") {
            // do somehting with closure
            args.first().call()
        }
    }
}

def a = new A()

a.ant { println "hello"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM