Groovy Explore the Mop 12 method call Order

Source: Internet
Author: User

We know that in addition to using hooks to intercept methods, we can also implement methods in various ways. For example, we can implement the method directly in the class, we can add the method through the Expandometaclass during the runtime, and we can add the method to an object separately by Expandometaclass during the run time.

All of these ways of directly adding methods, if there is a hook, are to be intercepted by hooks. So, we can say that the system is a priority call hook.

and the call order of the hooks, which we covered in the mop 11 run period of groovy exploration, InvokeMethod, has been discussed.

In this article, it is a question of the order of invocation of methods other than the Hook method.

We all know that if there is a class as follows:

class Foo {
def getFoo()
{
'foo'
}
}

So, we can call it by using the following methods:

def foo = new Foo()
println foo.foo

The results of the operation are:

Foo

This is our gpath.

Of course, we can also add this "get" method through Expandometaclass during the runtime, as follows:

Foo.metaClass.getFoo = {
->
'meta'
}

If we do the following test:

def foo = new Foo()
println foo.foo

Then, the result of the operation is:

Meta

As you can see from the results, the method that is added through Expandometaclass during the run time is the method that overrides the class itself.

We know that there is another way to add a method to a class during the run time, namely:

def mc = new ExpandoMetaClass(Foo.class,true)
mc.getFoo = {
->
'far'
}
mc.initialize()

Next, I will add the above two methods to the Foo class above, and then test it to see what happens.

The code is as follows:

Foo.metaClass.getFoo = {
->
'meta'
}
def mc = new ExpandoMetaClass(Foo.class,true)
mc.getFoo = {
->
'far'
}
mc.initialize()
def foo = new Foo()
println foo.foo
}

The results of the operation are:

Far

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.