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

问题描述

我试图理解invokeMethod如何拦截Groovy中的方法调用。我似乎无法得到最基本的例子工作。

  

您需要调用 invokeMethod 截取后。

 类Person实现GroovyInterceptable {
def invokeMethod(String name ,args){
System.out.println调用invokeMethod $ name $ args
metaClass.getMetaMethod(name,args).invoke(this,args)
}

def greet(){
System.out.printlnHello from greet()
}
}

def p = new Person()
p.greet()

是的,您对 println 。必须使用SOP。

I am trying to understand how invokeMethod intercepts method calls in Groovy. I can't seem to get the most basic of examples working though.

class Person implements GroovyInterceptable {

    def invokeMethod(String name,args) {
        println "called invokeMethod $name $args"
    }

    def greet() {
        println "Hello from greet()"
    }

}

def p = new Person()
p.greet()

If I try and run this example I get the following error. What am I missing?

Caught: java.lang.StackOverflowError
java.lang.StackOverflowError
    at Person.invokeMethod(Person.groovy:4)
    at Person.invokeMethod(Person.groovy:4)
    at Person.invokeMethod(Person.groovy:4)
    ...
解决方案

You need to invoke the actual method from invokeMethod after the interception.

class Person implements GroovyInterceptable {
    def invokeMethod(String name,args) {
        System.out.println "called invokeMethod $name $args"
        metaClass.getMetaMethod(name, args).invoke(this, args)
    }

    def greet() {
        System.out.println "Hello from greet()"
    }
}

def p = new Person()
p.greet()

And yes you are correct about println. Have to use SOP.

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

07-29 23:49
查看更多