LoginSignup
2
1

More than 5 years have passed since last update.

はじめに

Groovyのすべてのクラスは暗黙的にgroovy.lang.GroovyObjectインタフェースを実装していて、GroovyObjectインタフェースにはMOP用のメソッドが定義されてます。

実装も、とてもシンプルです。
invokeMothod
set/getProperty
set/getMetaClass
→groovy.lang.MetaClass imprements MetaObject

かいてみる

mop.groovy
package co.jp.e2info.groovy

String.metaClass.define {
    hello { return "hello " + delegate }
    bye { return "bye " + delegate }
}

println "world".hello()
println "world".bye()

String.metaClass.and = {return delegate + it}

println "xxx".and("yyy")

/*
hello world
bye world
xxxyyy
*/

// groovy.lang.GroovyObject#invokeMethod 
class InvokeMethodSample{
    def invokeMethod(String method, Object params) {
        println method
        if(params != null){
            params.each{ println it }
        }
    }
    def getProperty(String property){
        println property
    }
}

def im1 = new InvokeMethodSample();
im1.aiueo("a", "b");

/*
aiueo
a
b
 */


// groovy.lang.GroovyObject#getProperty
def im2 = new InvokeMethodSample();
im2.name

/*
name 
*/
2
1
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
2
1