【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 使用 MetaClass 进行方法拦截 | 对象上拦截方法 | 类上拦截方法 )
文章目錄
- 一、使用 MetaClass 進行方法攔截
- 1、使用 MetaClass 在單個對象上進行方法攔截
- 2、使用 MetaClass 在類上進行方法攔截
- 二、完整代碼示例
- 1、對象方法攔截
- 2、類方法攔截
一、使用 MetaClass 進行方法攔截
MetaClass 可以定義類的行為 , 可以利用 MetaClass 進行方法攔截 ;
Groovy 對象 和 類 都可以獲取 MetaClass 對象 , 聲明 Srudent 類 , 以及創(chuàng)建 Student 對象 ,
class Student{def name;def hello() {System.out.println "Hello ${name}"} }def student = new Student(name: "Tom")1、使用 MetaClass 在單個對象上進行方法攔截
在 Groovy 對象上獲取的元類對象 ,
student.metaClass攔截 MetaClass 上的方法 , 使用
元類對象名.方法名 = {閉包}即可攔截指定的方法 , 如下攔截 Student student 對象的 hello 方法 :
student.metaClass.hello = {println "Hello student.metaClass.hello" }執(zhí)行 hello 方法時 , 執(zhí)行的是閉包的內(nèi)容 , 不再是原來的 hello 方法內(nèi)容 ;
2、使用 MetaClass 在類上進行方法攔截
在 Groovy 類上獲取的元類對象 ,
Student.metaClass攔截 MetaClass 上的方法 , 使用
元類對象名.方法名 = {閉包}進行攔截 , 攔截 MetaClass 類上的方法 , 如 :
// 攔截 student 對象上的方法 Student.metaClass.hello = {println "Hello student.metaClass.hello" }特別注意 : 必須在創(chuàng)建對象之前 , 攔截指定的方法 , 在創(chuàng)建對象之后攔截 , 沒有任何效果 ;
二、完整代碼示例
1、對象方法攔截
創(chuàng)建 222 個 Student 對象 , 使用 MetaClass 在其中一個對象上攔截 hello 方法 , 執(zhí)行兩個對象的 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" }// 直接調(diào)用 hello 方法 student.hello() student2.hello()執(zhí)行結(jié)果 :
Hello student.metaClass.hello Hello Jerry2、類方法攔截
創(chuàng)建 222 個 Student 對象 , 使用 MetaClass 在類上攔截 hello 方法 , 執(zhí)行兩個對象的 hello 方法 , 兩個對象的 hello 方法都被攔截 ;
特別注意 : 必須在創(chuàng)建對象之前 , 攔截指定的方法 , 在創(chuàng)建對象之后攔截 , 沒有任何效果 ;
代碼示例 :
class Student{def name;def hello() {System.out.println "Hello ${name}"} }// 攔截 student 對象上的方法 // 特別注意 : 必須在創(chuàng)建對象之前攔截方法 // 創(chuàng)建對象之后再攔截方法 , 沒有效果 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// 直接調(diào)用 hello 方法 student.hello() student2.hello()執(zhí)行結(jié)果 :
Hello student.metaClass.hello Hello student.metaClass.hello總結(jié)
以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 使用 MetaClass 进行方法拦截 | 对象上拦截方法 | 类上拦截方法 )的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Groovy】MOP 元对象协议与元编
- 下一篇: 【Groovy】MOP 元对象协议与元编