The mop of groovy exploration for the dynamics of interface types

Source: Internet
Author: User

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

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.