1. 程式人生 > >Groovy動態建立類、方法合成、方法委託

Groovy動態建立類、方法合成、方法委託

/**
 * 動態生成類
 */
def expando = new Expando(name : 'hello',fun1:{int a,int b -> a*b})
expando.height = 100
expando.fun2 = {
    int a,int b->
        a+b
}
println expando.name
println expando.height
println expando.fun1(2,6)
println expando.fun2(2,6)

/**
 * 方法合成
 */
class MyPerson{
    def methodMissing(String name, def 
args) { println 'missing' if (name.startsWith('play')){ //生成的class檔案 呼叫方式不一樣 // println metaClass MyPerson p = this // println p.metaClass p.metaClass."$name" = { println "invoke $name" } "$name"(args) } return null } } def
p = new MyPerson() p.playGame() p.playGame() /** * 方法委託 */ class Work1{ def fun(){ println('work1') } } class Work2{ def fun2(){ println('work2') } } class WorkManager{ { delegate(Work1,Work2) } def delegate(Class... classes){ def objects = classes.collect{it.newInstance()} WorkManager workManager = this
workManager.metaClass.methodMissing = { String name,def args-> def object = objects.find{it.respondsTo(name,args)} if(object){ //動態注入方法 workManager.metaClass."$name" = { object.invokeMethod(name,args) } invokeMethod(name,args) } } } } def wm = new WorkManager() wm.fun() wm.fun2() //第二種方法 groovy自帶的註解 class WorkManager1{ @Delegate Work1 work1 = new Work1() @Delegate Work2 work2 = new Work2() } new WorkManager1().fun() new WorkManager1().fun2()