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()

你可能感兴趣的:(Gradle学习)