So far, our MOP series has talked about all aspects of using expandometaclass, but it's worth noting that we add a method to a class at run time by Expandometaclass. Whether it's a normal method or a static method, we add a method that determines the name of the method. That is, we add a method named A, and then we can use this method a.
However, the dynamic nature of the method name is actually something we have already contacted, such as in the InvokeMethod method of groovy exploration, we can create a beautiful method like "Sortbyxxxxx". Of course, in that text, we are through the "InvokeMethod" method to achieve.
As we all know, using Expandometaclass to add a method to an object or class in the runtime is much simpler than the hook method, so we use expandometaclass more often in the actual coding process. So, do we use Expandometaclass to implement the dynamic of the method name implemented by the hook method above?
We know that using Expandometaclass to add a method (either to the object or to the class) during the runtime, the form looks like this:
Class name. Metaclass. Method name = Method body
At the same time, the formula above can also be written as follows:
Class name. Metaclass. "Method Name" = Method body
Now that we understand that the method name can be enclosed in double quotes, then if the double quotes are inside a Gstring object, then we can give the method a variable data. This achieves the purpose of using Expandometaclass to implement the dynamic nature of the method name.
Cut the crap, let's take a look at an example first!
Now, we have a T class, as follows:
class T
{
}
We can add a method to the T class like this:
String functionName = "a";
T.metaClass."$functionName" = {
println "invoke $functionName"
}
def t = new T()
t.a()
When we add a method, we use a Gstring object instead of the dead string, thus implementing the dynamic of the method name. The results of the operation are:
invoke a
Of course, you may feel that the above method name dynamic is not clear enough, then, we can implement a static method as follows, to achieve the purpose of our method name dynamic:
def static add(functionName)
{
T.metaClass."$functionName" = {
println "invoke $functionName"
}
}
In this way, we can use it as follows:
add('b')
def t1 = new T()
t1.b()
add('c')
def t2 = new T()
t2.c()
The results of the operation are:
invoke b
invoke c