Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

What are meta-annotations ?

Meta-annotations, also known as annotation aliases are annotations that are replaced at compile time by other annotations (one meta-annotation is an alias for one or more annotations). This feature was added in Groovy 2.1.0. It can be used to dramatically reduce the verbosity of code involving multiple annotations.

Writing a meta-annotation

Let's start with a simple example. Imagine you have the @Service and @Transactional annotations and that you want to annotate a class with both:

Code Block
@Service
@Transactional
class MyTransactionalService {}

What meta-annotations allows you is to replace the two annotations by a single one. First of all, you need to define your alias:

Code Block
import groovy.transform.AnnotationCollector
 
@Service
@Transactional
@AnnotationCollector
public @interface TransactionalService {
}

We are defining a @TransactionalService annotation here, a meta-annotation, that collects the @Service and @Transactional annotations. This is done by annotating the interface with @AnnotationCollector.

Understanding the behaviour

Before going further, we have to understand how meta-annotations work. First of all, Groovy supports both precompiled and source form meta-annotations. This means that your meta-annotation may be precompiled, or you can have it in the same source tree as the one you are currently compiling. Second, this is a Groovy feature only. There is no chance for you to annotate a Java class with a meta-annotation and hope it will do the same as in Groovy. Likewise, you cannot write a meta-annotation in Java: both the meta-annotation definition and usage have to be Groovy code.

When the Groovy compiler encounters a class annotated with a meta-annotation, it replaces it with the collected annotations. That is, in our previous example, that it will replace @TransactionalService with @Transactional and @Service. This happens during the semantic analysis phase, that is to say exactly when AST transformations are collected. 

More than replacing the alias, a meta-annotation is capable of processing the collected annotations, including processing arguments. The default processor includes interesting behaviour with regards to annotation parameters.

Meta-annotation parameters

Here, we will imagine two annotations, each of them taking one argument:

Code Block
@Timeout(after=100)
@Dangerous(type="explosive")

And that you want create a meta-annotation named @Explosive:

Code Block
@Timeout(after=100)
@Dangerous(type="explosive")
@AnnotationCollector
public @interface Explosive {}

Then, by default, when the annotations are replaced, they will get the values as they were defined in the alias. More interesting, the alias supports overriding specific values:

Code Block
@Explosive(after=0)
class Bomb {}

Here, the value provided as a parameter to @Explosive overrides the one defined in the annotation.

Name clashes

What happens if two annotations define the same parameter name? The default processor will copy the annotation value to all annotations that accept this parameter. Take this example (you can run it in a Groovy console, for example):

Code Block
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
@Retention(RetentionPolicy.RUNTIME)
public @interface Foo {
   String value()
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Bar {
    String value()
}
@Foo
@Bar
@groovy.transform.AnnotationCollector
public @interface FooBar {}
@Foo('a')
@Bar('b')
class Bob {}
println Bob.class.getAnnotation(Foo)
println Bob.class.getAnnotation(Bar)
@FooBar('a')
class Joe {}
println Joe.class.getAnnotation(Foo)
println Joe.class.getAnnotation(Bar)

this would print:

Code Block
@Foo(value=a)
@Bar(value=b)
@Foo(value=a)
@Bar(value=a)

which means that in the second case, the annotation value was copied in both annotations. But what happens if, for example, the annotation type for Foo is String, and the one for Bar is an integer? The current behaviour of the annotation is to fail at compile time. Does it mean that there's nothing more you can do? No. Meta-annotations support a special feature called a processor, that will help you deal with such problems.

Custom annotation processors

A custom annotation processor will let you choose how to explode a meta-annotation. The behaviour of the meta-annotation is, in this case, totally up to you. You can do whatever you want. Let's take a look, for example, on how @CompileDynamic is implemented in Groovy 2.1.0. @CompileDynamic is a meta-annotation that replaces itself with @CompileStatic(TypeCheckingMode.SKIP). The problem is that the default meta annotation processor doesn't support enums and we need to produce that enum. So, instead of defining @CompileDynamic like this:

Code Block
@CompileStatic(TypeCheckingMode.SKIP)
@AnnotationCollector
public @interface CompileDynamic {}

We will define it like this:

Code Block
@AnnotationCollector(processor = "org.codehaus.groovy.transform.CompileDynamicProcessor")
public @interface CompileDynamic {
}

The first thing you may notice is that our interface is no longer annotated with @CompileStatic. The reason for this is that we rely on the extra processor parameter, that references a class which will generate the annotation. And here is what this class looks like:

Code Block
public class CompileDynamicProcessor extends AnnotationCollectorTransform {
    private static final ClassNode COMPILESTATIC_NODE = ClassHelper.make(CompileStatic.class);
    private static final ClassNode TYPECHECKINGMODE_NODE = ClassHelper.make(TypeCheckingMode.class);
    public List<AnnotationNode> visit(AnnotationNode collector, AnnotationNode aliasAnnotationUsage, AnnotatedNode aliasAnnotated, SourceUnit source) {
        AnnotationNode node = new AnnotationNode(COMPILESTATIC_NODE);
        node.addMember("value", new PropertyExpression(new ClassExpression(TYPECHECKINGMODE_NODE), "SKIP"));
        return Collections.singletonList(node);
    }
}

Our custom processor extends the default one and overrides the public List<AnnotationNode> visit(AnnotationNode collector, AnnotationNode aliasAnnotationUsage, AnnotatedNode aliasAnnotated, SourceUnit source) method. This method is responsible for returning the list of annotations that will be added to the AST tree in place of the alias. The body of this method, hence, is only there to generate the appropriate AnnotationNode, nothing more! Of course, you can rely on the superclass to deal with arguments, for example.