DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Groovy Goodness: Combining Annotations with AnnotationCollector

Groovy Goodness: Combining Annotations with AnnotationCollector

Hubert Klein Ikkink user avatar by
Hubert Klein Ikkink
·
Feb. 19, 13 · Interview
Like (0)
Save
Tweet
Share
6.86K Views

Join the DZone community and get the full member experience.

Join For Free

Groovy 2.1 introduces a new annotation to group multiple annotations and define an alias for the group. The new @AnnotationCollector annotation is an AST transformation. If we repeatedly have to add multiple annotations we can now create an alias for the multiple annotations and use it in our code.

We can define the group of annotations as an argument for the @AnnotationCollector annotations. For example in the next sample code we create an annotation to apply the @EqualsAndHashCode and @ToString annotations and use the alias Simple. We pass a list of annotations to the @AnnotationColletor:

@AnnotationCollector([EqualsAndHashCode, ToString])
@interface Simple {}


@Simple
class User {
    String username
    int age
}

def user = new User(username: 'mrhaki', age: 39)
assert user.toString() == 'User(mrhaki, 39)'

// We still have 2 annotations:
assert User.class.annotations.size() == 2


// We can use the attributes from the 
// grouped annotations.
@Simple(excludes = 'street') 
class Address {
    String street, town
}

def address = new Address(street: 'Evergreen Terrace', town: 'Springfield') 
assert address.toString() == 'Address(Springfield)'

Notice we can also use the attributes from the grouped annotations. If an attribute cannot be mapped to the existing attributes of the grouped annotations we get an error. We can write custom code to handle new attributes in a so-called processor class. In the processor we can define how we want to handle the attributes. In the following sample we define a custom attribute dontUse and we use the value for the excludes attribute of the grouped annotations:

import org.codehaus.groovy.transform.*
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.*

class SimpleProcessor extends AnnotationCollectorTransform {

    public List<AnnotationNode> visit(AnnotationNode collector, 
                                      AnnotationNode aliasAnnotationUsage, 
                                      AnnotatedNode aliasAnnotated, 
                                      SourceUnit source) {
                                      
        // Get attributes and attribute value for dontUse.
        def attributes = aliasAnnotationUsage.getMembers()
        def dontUse = attributes.get('dontUse')
        attributes.remove('dontUse')
        
        if (dontUse) {
            // Assign value of dontUse to excludes attributes.
            aliasAnnotationUsage.addMember("excludes", dontUse)
        }
        
        super.visit(collector, aliasAnnotationUsage, aliasAnnotated, source)
    }    
    
}

new GroovyShell(this.class.classLoader).evaluate '''
import groovy.transform.*

@AnnotationCollector(value = [EqualsAndHashCode, ToString], processor = 'SimpleProcessor')
@interface Simple {}


@Simple(dontUse = 'age')
class User {
    String username
    int age
}

def user = new User(username: 'mrhaki', age: 39)
assert user.toString() == 'User(mrhaki)'
'''

Another way to define an alias for a group of annotations is to simply define an annotation, add the annotations we want to group and as last annotation we add the @AnnotationCollector. In the next sample we combine the @Grapes and @Slf4j annotations into the alias LoggingSlf4j:

// Add dependencies for Slf4j API and Logback
import org.slf4j.*
import groovy.util.logging.Slf4j
import groovy.transform.*

@Grapes([
    @Grab(group='org.slf4j', module='slf4j-api', version='1.6.1'),
    @Grab(group='ch.qos.logback', module='logback-classic', version='0.9.28')
])
@Slf4j
@AnnotationCollector
@interface LoggingSlf4j {}


// Use annotation to 'grab' dependencies and
// inject log field into the class.
@LoggingSlf4j
class HelloWorldSlf4j {
    def execute() {
        log.debug 'Execute HelloWorld.'
        log.info 'Simple sample to show log field is injected.'
    }
}

def helloWorld = new HelloWorldSlf4j()
helloWorld.execute()  
// Output:
// 05:40:57.724 [Thread-19] DEBUG HelloWorldSlf4j - Execute HelloWorld.
// 05:40:57.724 [Thread-19] INFO  HelloWorldSlf4j - Simple sample to show log field is injected.

More info and samples are also available on the blog of Andres Steingress.

Written with Groovy 1.2.



 

Annotation Groovy (programming language)

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • API Design Patterns Review
  • How Observability Is Redefining Developer Roles
  • How to Create a Real-Time Scalable Streaming App Using Apache NiFi, Apache Pulsar, and Apache Flink SQL
  • Bye Bye, Regular Dev [Comic]

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: