12.1Groovy使用GroovyInterceptable拦截方法
2017-11-21 08:58
183 查看
如果一个Groovy对象实现了GroovyInterceptable接口,在调用他的任何方法时,都会被invokeMethod()方法拦截。对于在Groovy对象中没有的方法,可以通过MetaClass对象的invokeMethod()方法拦截。
运行结果:
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()
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()
相关文章推荐
- Groovy探索 使用集合方法,写出更加Groovy风格的代码
- Groovy探索之闭包 七 使用闭包来实现模板方法模式
- Groovy高效编程——‘匕首方法’的使用
- IDEA使用 live template添加groovy脚本给方法,类,js方法添加注释(转载)
- Groovy高效编程——‘匕首方法’的使用
- Groovy优势2——使用call方法
- Groovy高效编程——‘匕首方法’的使用
- Groovy探索 使用集合方法,写出更加Groovy风格的代码
- Groovy高效编程——‘匕首方法’的使用
- groovy 的inject()方法使用简例
- Groovy高效编程——‘匕首方法’的使用(更新于2007.09.14)(转载)
- Groovy高效编程——‘匕首方法’的使用
- Groovy高效编程——‘匕首方法’的使用
- Groovy高效编程——‘匕首方法’的使用
- 【SoapUI】在soapui中使用Groovy脚本常用方法
- 【Groovy】List对象的transpose和inject方法的使用
- Jakarta Commons Digester 简介和具体使用方法
- 简介使用ASP.NET访问Oracle数据库的方法
- 使用面向oo对象方法的12个优点
- 水晶报表使用经验谈1--建立水晶报表第一步及编译最易出现错误的解决方法及报表转换成pdf文档进行打印方法