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)
}
}