The interface type described here, in both the Java language and the groovy language, is of course both the base class type and the interface. The term "Dynamic of an interface type" refers to the dynamic addition of a method to a base class or interface during the runtime so that the base class and its subclasses, interface implementations, can access these methods.
This feature has always been a feature of interest to me. Because we use a variety of application APIs in our programming practices, as well as JDK, there may be interfaces and their subclasses that we use frequently in the process of using them, but we feel very inconvenient in the process of using them. At this point, we can use the categories mechanism to expand the class we are using, but if a class has a few subclasses or an interface with several implementations, we all want the same extensions for all subclasses or implementations. So, if we use the categories mechanism, we have to expand all subclasses or implementations sequentially. This has resulted in repetitive labor.
When we use the Expandometaclass mechanism, we only need to extend the function of the base class or interface, so all subclasses or implementations can get that functionality. What a thrill it is!
First, let's look at an example of a base class and its subclasses.
We already have one of the following base classes:
class A
{
def afuction()
{
println 'a'
}
}
At the same time, we have several subclasses of it, and here's an example:
class B extends A
{
def bfuction()
{
println 'b'
}
}
Now, we want to add a method to Class A in the runtime, and the B class has the method.
First, make Expandometaclass enabled globally:
ExpandoMetaClass.enableGlobally()
Next, we add a method to Class A:
A.metaClass."aAndb" = {
->
println 'a and b'
}
Below, we can test:
def a = new A()
a.aAndb()
def b = new B()
b.aAndb()
The results of the operation are:
a and b
a and b