We have long used the groovy language hook, the "InvokeMethod" method and several other methods. We implement the "InvokeMethod" method in a class that assigns all or part of the methods of the class instance that are invoked during the run time. These are discussed in detail in the mop InvokeMethod and methodmissing methods of groovy exploration.
Now, we have been in deep contact with the metaclass of the groovy language, but also the use of expandometaclass everywhere. As we all know, the flexibility of expandometaclass is not comparable to hooks. We thought that since using Expandometaclass to add a method to a class during the run time, would we be able to increase the hook method during the runtime?
We can answer, yes. Let's look at a simple example first!
We still have such a simple class:
class Foo
{
def foo()
{
'foo'
}
}
We are now trying to increase the "InvokeMethod" method during the run period:
Foo.metaClass.invokeMethod = {
String name,args1 ->
'test'
}
Next, we test the added "InvokeMethod" method during this runtime:
def foo = new Foo()
println foo.foo()
println foo.test()
The results of the operation are:
test
test
As you can see, the "InvokeMethod" method we added during the runtime intercepts all the methods of an instance of the Foo class.
Of course, if we want to block the "InvokeMethod" method, the method already exists in the Foo class, such as "Foo", to the Foo class itself to deal with the method. So, we can implement the "InvokeMethod" method as follows:
Foo.metaClass.invokeMethod = {
String name,args1 ->
def m = Foo.metaClass.getMetaMethod(name,args1)
def result
if(m)
result = m.invoke(delegate,args1)
else
result = 'test'
result
}
When we run the test code above, we get the following results:
foo
test