日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 重写 MetaClass#invokeMethod 方法拦截 JDK 中已经定义的函数 )

發布時間:2025/6/17 40 豆豆

文章目錄

  • 一、重寫 MetaClass#invokeMethod 方法攔截 JDK 中已經定義的函數
    • 1、被攔截的 String#contains 方法原型
    • 2、JDK 正常用法
    • 3、攔截 String 對象的 contains 函數
    • 4、重寫 MetaClass#invokeMethod 方法進行函數攔截





一、重寫 MetaClass#invokeMethod 方法攔截 JDK 中已經定義的函數



重寫 MetaClass#invokeMethod 方法 , 不僅可以攔截自定義的類中的方法 , 還可以攔截 JDK 中已經定義完畢的方法 ;

如果要攔截 JDK 中的方法 , 肯定不能使用 實現 GroovyInterceptable 接口的方法 , 只能使用重寫 MetaClass#invokeMethod 方法進行攔截 ;


此處以 String 類為例 , 攔截其中的 contains 方法 , 查詢 String 常量 “Hello World” 中是否包含某個子串 “Hello” ;


1、被攔截的 String#contains 方法原型


被攔截方法原型 :

public final class Stringimplements java.io.Serializable, Comparable<String>, CharSequence {/*** 當且僅當此字符串包含指定的字符值序列時,返回true。** @param s 要查找的字符串* @return 如果字符串中包含要查找的字符串返回 true , 反之返回 false* @since 1.5*/public boolean contains(CharSequence s) {return indexOf(s.toString()) > -1;} }

2、JDK 正常用法


正常用法 : 使用 JDK 中的 String 類中定義的 contains 方法 , 查詢字符串中是否包含指定的子串 ;

def string = "Hello World"// 查詢字符串中是否包含 "Hello" 字符串 def flag = string.contains("Hello") println flag

執行結果 :

true

3、攔截 String 對象的 contains 函數


為 string.metaClass.contains 賦值一個閉包 , 在閉包中接收 CharSequence s 參數 , 這個參數就是傳入的要查找的子串 ;


代碼示例 :

def string = "Hello World"string.metaClass.contains = {CharSequence s->System.out.println "Is \"$string\" contains \"$s\""true }// 查詢字符串中是否包含 "Hello" 字符串 def flag = string.contains("Hello") println flag

執行結果 :

Is "Hello World" contains "Hello" true

4、重寫 MetaClass#invokeMethod 方法進行函數攔截


使用下面的方法可以攔截所有的函數 ;

def string = "Hello World"string.metaClass.invokeMethod = {String name, Object args ->System.out.println "invokeMethod : Object : $string , Method name : $name , Object args : $args"// 方法轉發 : 調用 string 對象中的原來的方法// 注意此處不能使用 metaClass.invokeMethod 方法調用對象中的方法 , 會導致棧溢出// 這里通過 MetaClass#getMetaMethod 獲取方法 , 然后執行def method = delegate.metaClass.getMetaMethod(name, args)// 方法不為空再執行該方法if (method != null) {method.invoke(delegate, args)} }// 查詢字符串中是否包含 "Hello" 字符串 def flag = string.contains("Hello") println flag

執行結果 :

invokeMethod : String name : contains , Object args : [Hello] true

總結

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

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