The "Interceptor" in this article is mainly about intercepting the interceptor, which is one of the challenges we often encounter when customizing interceptors.
One of the things that is close to blocking is not intercepting, that is, we can intercept a method, but we do not do any real action on interception, that is, we simply release the interception action. This is a passive and not interception behavior. And our blocking interception is more proactive, that is, the interceptor is not intercepted to a method.
Below, we will give an example of release interception and blocking interception respectively.
First, let's design a class that needs to be intercepted:
class Foo {
def foo()
{
println 'foo'
}
def bar()
{
println 'bar'
}
}
If we don't want to intercept the bar method and just block the "foo" method, we can design the interceptor like this:
class NoBarInterceptor implements Interceptor{
Object beforeInvoke(Object object, String methodName, Object[] arguments){
if(methodName == 'foo')
{
println 'interceptor the function: foo'
}
}
boolean doInvoke(){ true }
Object afterInvoke(Object object, String methodName, Object[] arguments,
Object result){
result
}
}
In the code, we only intercept methods named "Foo", and other methods are not processed, that is, release. Let's write a little bit of test code:
def proxy= ProxyMetaClass.getInstance( Foo )
proxy.interceptor= new NoBarInterceptor()
proxy.use{
def f= new Foo()
f.foo()
f.bar()
}
The results of the operation are:
interceptor the function: foo
foo
bar
Of course, if we want to be more proactive in determining which methods to release, we can design our interceptors this way:
class NoMethodInterceptor implements Interceptor{
def methods
Object beforeInvoke(Object object, String methodName, Object[] arguments){
if(!(methodName in this.methods))
{
println "before invoking $methodName"
}
null
}
boolean doInvoke(){ true }
Object afterInvoke(Object object, String methodName, Object[] arguments,
Object result){
result
}
}