gpt4 book ai didi

groovy - 有没有办法拦截 Groovy 中的所有方法调用?

转载 作者:行者123 更新时间:2023-12-03 09:24:22 25 4
gpt4 key购买 nike

我需要拦截预定义 Java 类上的方法调用。例如,假设我需要拦截 String 类 split 方法,我该怎么做?

我试过this这是可行的,但我不希望最终用户通过使用代理 block 包装他们的调用来更改他们的代码。

有什么方法可以用 Groovy 来实现这一点吗?

最佳答案

如果您想要拦截对特定方法的调用,您可以执行以下操作...

// intercept calls to the split method on java.lang.String
String.metaClass.split = { String arg ->
// do whatever you want to do
}

如果您想要做的是拦截对特定方法的调用,并在调用原始方法之外执行一些操作(例如用您自己的一些逻辑包装真正的方法),您可以执行以下操作:

// get a reference to the original method...
def originalSplit = String.metaClass.getMetaMethod('split', [String] as Class[])

// now add your own version of the method to the meta class...
String.metaClass.split = { String arg ->
// do something before invoking the original...

// invoke the original...
def result = originalSplit.invoke(delegate, arg)

// do something after invoking the original...

// return the result of invoking the original
result
}

希望对您有所帮助。

关于groovy - 有没有办法拦截 Groovy 中的所有方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24502300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com