您的位置:首页 > 其它

12.1Groovy使用GroovyInterceptable拦截方法

2017-11-21 08:58 183 查看
如果一个Groovy对象实现了GroovyInterceptable接口,在调用他的任何方法时,都会被invokeMethod()方法拦截。对于在Groovy对象中没有的方法,可以通过MetaClass对象的invokeMethod()方法拦截。

class Car implements GroovyInterceptable{ // 实现GroovyInterceptable接口
def check(){System.out.println "check called..." } // 检查
def start(){System.out.println "start called..." } // 启动
def drive(){System.out.println "drive called..." } // 驾驶

// 劫持方法(拦截Car类所有的方法)
def invokeMethod(String name, args) {
System.out.print("Call to $name intercepted...") // 呼叫拦截

if (name != 'check') {
System.out.print("running filter...") // 过滤器
Car.metaClass.getMetaMethod('check').invoke(this, null) // 调用前置过滤(check()方法)
}

// 如果Car类么有的方法,则路由给MetaClass
def validMethod = Car.metaClass.getMetaMethod(name, args)
if (validMethod != null) {
validMethod.invoke(this, args)
} else {
Car.metaClass.invokeMethod(this, name, args)
}
}
}

car = new Car()

car.start()
car.drive()
car.check()

try {
car.speed() // 调用Car类中不存在的方法,会被拦截
} catch (Exception e) {
println e
}

运行结果:

Call to start intercepted...running filter...check called...

start called...

Call to drive intercepted...running filter...check called...

drive called...

Call to check intercepted...check called...

Call to speed intercepted...running filter...check called...

groovy.lang.MissingMethodException: No signature of method: Car.speed() is applicable for argument types: () values: []

Possible solutions: sleep(long), sleep(long, groovy.lang.Closure), split(groovy.lang.Closure), check(), start(), grep()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: