LoginSignup
1
0

More than 5 years have passed since last update.

GroovyでClosureのdoCallをMetaClassで足す

Posted at

注意:
この内容は実用される事を意図した内容ではありません。
実際に使う場合はご自身の責任にてご利用下さい。

はじめに

GroovyのClosureのcall()は、doCall()をMetaClass経由で呼び出しています。参考
doCall()に、Closure個別の処理が書かれています。( {->(doCallはここに相当)} )

このdoCallをMetaClassで足してしまおう、と言う話です。

製作

Step 1: おまじない

ClosureのMetaClassを扱うなら基本中の基本(?)

ExpandoMetaClass.enableGlobally()

Step 2: doCall無しClosureを作る

  1. コンストラクタを適切に扱う
  2. 匿名クラスとする(中身はもちろん空)

これだけ守れば問題なくClosureを作れます

def closure=new Closure(this,this){}

Step 3: doCallを足す

closure.metaClass.doCall={->println 'Called'}

Step 4: 呼ぶ

closure()// Called

最後に

よいこのみんなは{->}を使おうね

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0