class Chinese { def chineseTech() { PRintln "Chinese Teacher do the work" }}class English { def englishTech() { println "Chinese Teacher do the work" }}class Math { def mathTech() { println "Chinese Teacher do the work" }}class Teacher { Teacher() { delegateTo Chinese, English, Math } def delegateTo(Class... classes) { def objOfDelegate = classes.collect { it.newInstance() } Teacher instance = this instance.metaClass.methodMissing = { String name, args -> println "In methodMissing" def delegate = objOfDelegate.find { it.metaClass.respondsTo(it, name, args) } if (delegate) { instance.metaClass."$name" = { Object[] vargs -> delegate.invokeMethod(name, vargs) } delegate.invokeMethod(name, args) } else { println "no delegate" } } }}tech = new Teacher();tech.chineseTech()tech.englishTech()tech.mathTech()tech.mathTech()tech.physicsTech()返回In methodMissingChinese Teacher do the workIn methodMissingChinese Teacher do the workIn methodMissingChinese Teacher do the workIn methodMissingno delegate
新闻热点
疑难解答