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

问题描述

我有一个java对象的实例,让我们说一个ArrayList实例,称为myList。

对于这个特定的实例,我想重写invokeMethod方法为(说)记录该方法被调用。

我可以这样做:

  myList.metaclass.invokeMethod {name,args  - > 
$ b println用$ {args}调用$ {name}
whatGoesHere.invokeMethod(name,args)

}

注意封闭的第二行 - 我怎样才能调用原始的invokeMethod方法?我是否正确地做了这件事?

解决方案

原始方法可能有一条较短的路线, p>

  def myList = [1,2,3] 

myList.metaClass.invokeMethod {name,args - >
println用$ {args}调用$ {name}
delegate.class.metaClass.getMetaMethod(name,args)?。invoke(delegate,args)
}

myList.sum()


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

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

I could do something like this:

myList.metaclass.invokeMethod { name, args -> 

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

}

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 14:46