文章目录
一、GroovyInterceptable 接口简介
定义 Groovy 类时 , 令该类实现 GroovyInterceptable 接口 , 该 GroovyInterceptable 接口继承自 GroovyObject 接口 ,
public interface GroovyInterceptable extends GroovyObject {
}
由上面的代码可知 , 在 GroovyInterceptable 接口中 , 没有在 GroovyObject 接口 的基础上 , 定义新的抽象方法 ;
二、重写 GroovyObject#invokeMethod 方法
定义 Student 实现 GroovyInterceptable 接口 ,
class Student implements GroovyInterceptable{
def name;
def hello() {
println "Hello ${name}"
}
}
那么调用 Student 对象的任何方法 , 都会调用到 GroovyObject 的 invokeMethod 方法 ;
public interface GroovyObject {
/**
* Invokes the given method.
*
* @param name the name of the method to call
* @param args the arguments to use for the method call
* @return the result of invoking the method
*/
Object invokeMethod(String name, Object args);
}
重写 Student 类中的 invokeMethod 方法 ,
class Student implements GroovyInterceptable{
def name;
def hello() {
println "Hello ${name}"
}
@Override
Object invokeMethod(String name, Object args) {
System.out.println "invokeMethod"
}
}
三、GroovyInterceptable 接口拦截效果
GroovyInterceptable 接口 :
-
没有实现 GroovyInterceptable 接口 :
- 直接调用方法 : 不会触发 invokeMethod 方法 ;
- 通过 invokeMethod 调用方法 : 会触发 invokeMethod 方法 ;
- 调用不存在的方法 : 会报错 ;
-
实现了 GroovyInterceptable 接口 :
- 直接调用方法 : 会触发 invokeMethod 方法 ;
- 通过 invokeMethod 调用方法 : 会触发 invokeMethod 方法 ;
- 调用不存在的方法 : 不会报错 ;
四、完整代码示例
完整代码示例 :
class Student implements GroovyInterceptable{
def name;
def hello() {
println "Hello ${name}"
}
@Override
Object invokeMethod(String name, Object args) {
System.out.println "invokeMethod : $name"
}
}
def student = new Student(name: "Tom")
// 直接调用 hello 方法
student.hello()
// 调用不存在的方法 , 也会触发 invokeMethod 方法
student.hello1()
执行结果 :
invokeMethod : hello
invokeMethod : hello1