Groovy Explore Mop 11 during run time coverage InvokeMethod

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.