在之前的博客中 , 主要是使用 Groovy 元编程 拦截方法 , 改变方法的实现 ;
使用元编程还可以为 Groovy 类 注入一个新的方法 , 方法注入 ;
Groovy 方法注入的
种方式 :
上述注入都是通过 运行时元编程 进行方法注入 , 编译时元编程 也可以进行方法注入 ;
定义 Student 类 ,
class Student {
def name;
}
定义 Hello 类 , 在该类中定义静态的注入方法 , 为 Student 类注入一个方法 , 注意参数必须是 Student 类型 ,
class Hello {
static def hello(Student self) {
System.out.println "Hello ${self.name}"
}
}
使用 use 代码块 , 调用被注入的方法 ,
use(Hello) {
new Student(name: "Tom").hello()
}
use 表示要使用 Hello 类中的注入方法 , 为 Student 类注入 Hello 类中的 hello 方法 , 在下图中可以看到 , 在 use 代码块中 , 可以提示出要注入的方法 ;
完整代码示例 :
class Student {
def name;
}
class Hello {
static def hello(Student self) {
System.out.println "Hello ${self.name}"
}
}
use(Hello) {
new Student(name: "Tom").hello()
}
执行结果 :
Hello Tom