日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 使用 MetaClass 进行方法拦截 | 对象上拦截方法 | 类上拦截方法 )

發布時間:2025/6/17 编程问答 20 豆豆

文章目錄

  • 一、使用 MetaClass 進行方法攔截
    • 1、使用 MetaClass 在單個對象上進行方法攔截
    • 2、使用 MetaClass 在類上進行方法攔截
  • 二、完整代碼示例
    • 1、對象方法攔截
    • 2、類方法攔截





一、使用 MetaClass 進行方法攔截



MetaClass 可以定義類的行為 , 可以利用 MetaClass 進行方法攔截 ;

Groovy 對象 和 類 都可以獲取 MetaClass 對象 , 聲明 Srudent 類 , 以及創建 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" }

執行 hello 方法時 , 執行的是閉包的內容 , 不再是原來的 hello 方法內容 ;


2、使用 MetaClass 在類上進行方法攔截


在 Groovy 類上獲取的元類對象 ,

Student.metaClass

攔截 MetaClass 上的方法 , 使用

元類對象名.方法名 = {閉包}

進行攔截 , 攔截 MetaClass 類上的方法 , 如 :

// 攔截 student 對象上的方法 Student.metaClass.hello = {println "Hello student.metaClass.hello" }

特別注意 : 必須在創建對象之前 , 攔截指定的方法 , 在創建對象之后攔截 , 沒有任何效果 ;





二、完整代碼示例




1、對象方法攔截


創建 222 個 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


2、類方法攔截


創建 222 個 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

總結

以上是生活随笔為你收集整理的【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 使用 MetaClass 进行方法拦截 | 对象上拦截方法 | 类上拦截方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。