Mop a InvokeMethod and methodmissing method of groovy exploration

Source: Internet
Author: User
Tags join

Finally, I talked about the mop features of the groovy language, and I talked about it sporadically in the previous chapters, but I never systematically talked about it. This is because the mop features of the groovy language are too flexible, such as the "InvokeMethod" and "methodmissing" approaches in this section, their functions are very similar, but the differences are quite subtle. However, in any case, the mop programming of the groovy language is what we have to master. And this series I didn't plan how many sections to talk about, like the "Groovy Explorer Closure" series, part of the exploration said.

The "InvokeMethod" approach discussed in this section has been discussed in a chapter in the Groovy Exploration series, and it's about the distinction between it and "methodmissing".

For the "InvokeMethod" method, we must be familiar with, we can use the following a simple example to see its role:

class InvokeTestor1 {

def hello()
{
'invoke hello directly'
}

def invokeMethod(String name,Object args)
{
return "unknown method $name(${args.join(',')})"
}

static void main(args) {

def it = new InvokeTestor1()

println it.hello()

println it.foo("mark",19)

}

}

The results of the run are:

invoke hello directly
unknown method foo(mark,19)

It can be seen that for the method invocation of an object, if the method can be assigned, as the "Hello" method above, it can be found in the InvokeTestor1 class and assigned to the "Hello" method of the InvokeTestor1 class; "Foo" method, the "InvokeMethod" method is invoked.

In the groovy language, there is also a way to implement the above function, this is the "methodmissing" method, see the following example:

class MethodTestor1 {

def hello()
{
"invoke hello directly"
}

def methodMissing(String name,args)
{
return "unknown method $name(${args.join(',')})"
}

static void main(args) {

def mt = new MethodTestor1()

println mt.hello()

println mt.foo('mark',19)

}

}

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.