MetaClass 可以定义类的行为 , 可以利用 MetaClass 进行方法拦截 ;
Groovy 对象 和 类 都可以获取 MetaClass 对象 , 声明 Srudent 类 , 以及创建 Student 对象 ,
class Student{
def name;
def hello() {
System.out.println "Hello ${name}"
}
}
def student = new Student(name: "Tom")
在 Groovy 对象上获取的元类对象 ,
student.metaClass
拦截 MetaClass 上的方法 , 使用
元类对象名.方法名 = {闭包}
即可拦截指定的方法 , 如下拦截 Student student 对象的 hello 方法 :
student.metaClass.hello = {
println "Hello student.metaClass.hello"
}
执行 hello 方法时 , 执行的是闭包的内容 , 不再是原来的 hello 方法内容 ;
在 Groovy 类上获取的元类对象 ,
Student.metaClass
拦截 MetaClass 上的方法 , 使用
元类对象名.方法名 = {闭包}
进行拦截 , 拦截 MetaClass 类上的方法 , 如 :
// 拦截 student 对象上的方法
Student.metaClass.hello = {
println "Hello student.metaClass.hello"
}
特别注意 : 必须在创建对象之前 , 拦截指定的方法 , 在创建对象之后拦截 , 没有任何效果 ;
创建
个 Student 对象 , 使用 MetaClass 在其中一个对象上拦截 hello 方法 , 执行两个对象的 hello 方法 , 只有前者的 hello 方法被拦截 ;
代码示例 :
class Student{
def name;
def hello() {
System.out.println "Hello ${name}"
}
}
def student = new Student(name: "Tom")
def student2 = new Student(name: "Jerry")
// Groovy 对象上获取的元类对象
student.metaClass
// Groovy 类上获取的元类
Student.metaClass
// 拦截 student 对象上的方法
student.metaClass.hello = {
println "Hello student.metaClass.hello"
}
// 直接调用 hello 方法
student.hello()
student2.hello()
执行结果 :
Hello student.metaClass.hello
Hello Jerry
创建
个 Student 对象 , 使用 MetaClass 在类上拦截 hello 方法 , 执行两个对象的 hello 方法 , 两个对象的 hello 方法都被拦截 ;
特别注意 : 必须在创建对象之前 , 拦截指定的方法 , 在创建对象之后拦截 , 没有任何效果 ;
代码示例 :
class Student{
def name;
def hello() {
System.out.println "Hello ${name}"
}
}
// 拦截 student 对象上的方法
// 特别注意 : 必须在创建对象之前拦截方法
// 创建对象之后再拦截方法 , 没有效果
Student.metaClass.hello = {
println "Hello student.metaClass.hello"
}
def student = new Student(name: "Tom")
def student2 = new Student(name: "Jerry")
// Groovy 对象上获取的元类对象
student.metaClass
// Groovy 类上获取的元类
Student.metaClass
// 直接调用 hello 方法
student.hello()
student2.hello()
执行结果 :
Hello student.metaClass.hello
Hello student.metaClass.hello