How do I create a simple annotation?

Metadata is a way to add some supplement information to the source code. This information is called annotation will not change how the program runs. This metadata can be used by other tools such as source code generator for instance to generate additional code at the runtime. Or it will be used by a dependency injection framework such as the Spring Framework.

The annotation can be attached to classes, methods, etc. To create an annotation we use the interface keyword and add an @ symbol in front of it. The @ symbol will tell the compiler that it is an annotation.

So now let us see the code for a simple annotation, a HelloAnnotation.

package org.kodejava.lang.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public @interface HelloAnnotation {
    String value();

    String greetTo();

All annotations extend the java.lang.annotation.Annotation interface, which means that java.lang.annotation.Annotation is the super-interface of all annotations

An annotation need to have a RetentionPolicy that will be the scope of the annotation where at this point the annotation will be ignored or discarded. The values are RetentionPolicy.SOURCE, RetentionPolicy.CLASS and RetentionPolicy.RUNTIME. When no retention policy defined it will use the default retention policy which is the RetentionPolicy.CLASS.

Annotation with RetentionPolicy.SOURCE retention policy will be retained only in the source code, it is available to the compiler when it compiles the class and will be discarded after that. The RetentionPolicy.CLASS retention policy will make the annotation stored in the class file during compilation, but will not available during the runtime. And the RetentionPolicy.RUNTIME retention policy will store the annotation in the class file during compilation, and it is also available to JVM at runtime.

In the example above you also see that the HelloAnnotation have two members value() and greetTo(). Annotations only have method declaration in it with no implementation body.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.