本文介绍了Groovy - 覆盖单个实例的 invokeMethod的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 java 对象的实例,假设有一个名为 myList 的 ArrayList 实例.

I have an instance of a java object, let's say an instance of ArrayList called myList.

对于这个特定的实例,我想覆盖 invokeMethod 方法来(比如)记录该方法被调用.

For this particular instance, I want to override the invokeMethod method to (say) log that method was called.

我可以这样做:

myList.metaclass.invokeMethod { name, args ->

   println "Called ${name} with ${args}"
   whatGoesHere.invokeMethod(name, args)

}

注意闭包的第 2 行 - 我如何调用原始的 invokeMethod 方法?我的做法正确吗?

Notice the 2nd line of the closure - how can I call the original invokeMethod method? Am I going about this correctly?

推荐答案

原来的方法可能有更短的路线,但这应该有效:

There might be a shorter route to the original method, but this should work:

def myList = [ 1, 2, 3 ]

myList.metaClass.invokeMethod { name, args ->
   println "Called ${name} with ${args}"
   delegate.class.metaClass.getMetaMethod( name, args )?.invoke( delegate, args )
}

myList.sum()

这篇关于Groovy - 覆盖单个实例的 invokeMethod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 22:52