首页 > 学院 > 开发设计 > 正文

Groovy动态委托

2019-11-08 01:16:21
字体:
来源:转载
供稿:网友

Groovy动态委托

将Teacher的工作委托给各个科目去完成。
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
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表