Reputation: 347
A class named InterceptorTest
implementing GroovyInterceptable
,which could be an interceptor,has its invokeMethod
overrided as follows:
class InterceptorTest implements GroovyInterceptable{
def invokeMethod(String name,args){
println "intercepting call! " //println a short message
}
}
I thought class InterceptorTest
to be an interceptor would delegate all method calls to invokeMethod
,so the following should work:
def interceptor=new InterceptorTest()
println interceptor.work()
Unfortunately, I got a StackOverflowError,seemingly at the body of invokeMethod
,but I had no clue why it happened.
As a counterpart, I altered the function body,not println
but just return
message:
class InterceptorTest implements GroovyInterceptable{
def invokeMethod(String name,args){
"intercepting call! " //return a short message
}
}
then it worked fine:
def interceptor=new InterceptorTest()
println interceptor.work() //get "intercepting call!"
But WHY?
Upvotes: 1
Views: 100
Reputation: 784
According to the documentation, "println" is actually a method in the class, injected by Groovy. Therefore, you achieve infinite recursion by trying to call it within the invokeMethod function.
We cannot use default groovy methods like println because these methods are injected into all Groovy objects so they will be intercepted too.
Upvotes: 1