How to Add Delegates to Classes in Groovy

  • google plus

In Brief...

Imagine being able to assign, i.e., delegate, methods of an existing class to a property in a Groovy class you are developing. Then you could leverage those methods as if they were a part of your new class! In addition, you wouldn't even have to reference the property directly, only the object. If the property name ever changed, you wouldn't need to maintain code that calls the delegate methods. In this topic we will use the @Delegate annotation to realize the benefits of using delegates. In our case, we will delegate the methods of the String class to a person's phone number.

Instructions

To learn how to add delegates to classes in Groovy, follow these 3 steps:

  1. Open your text editor and type in the following Groovy statements:
    // Define Person class 
    class Person {
    	String fullName
    	@Delegate String phoneNumber
    	String emailAddress
    	public String toString() {
    		"Name: $fullName Email: $emailAddress"
    	}	
    }
    // Create a person object
    def person = new Person(fullName : "Withrow/Stephen", phoneNumber: "4075554321", emailAddress: "sfw@webucator.com")
    // Display area code of phone number:
    println ("Area code: ${person.substring(0,3)}")
    // Display last 4 digits of phone number:
    println ("Last 4 digits displayed for security: ***-***-${person.substring(6)}")
    // Validate phone number (10 digits) using regular expression:
    println ("Phone number valid? ${person.matches("\\d{10}")}")
    // Finally, display the person
    println ("${person}")
    
    A Person class is defined in the script. Note that the phone number is annotated with @Delegate and is defined as type String. Therefore, the String methods are delegated (applied) to phoneNumber if any of the methods are called from a Person object. The script contains three examples of using the delegate methods. Note that phoneNumber is not referenced when calling a String method. Each public instance String method has actually been added to the class and the phone number is the target for each method,e.g., substring.
  2. Save your file as AddDelegatesToClasses.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run Add Delegates script
    The output shows the results of calling a few delegate methods and the toString method of the Person class.

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.

Categories

Courses

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss