java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 infront of it. The @ symbol will tell the compiler that it doing some business with an annotation.

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

package com.javacoderanch.example.annotation;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnno {
    String value();
    String greetTo();
}

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 SOURCE retention policy will be retained only in the source code, it available to the compiler when it compiles the class and will be discarded after that. The CLASS retention policy will make the annotation stored in the class file during compilation, but will not available during the runtime. And the RUNTIME retention policy will stored the annotation in the class file during compilation and it also available to JVM at runtime.

In the example above you also see that the HelloAnno have two members value() and greetTo(). Annotations only have a methods declaration in it with no implementation body. All annotations are extending the java.lang.annotation.Annotation interface, which means that java.lang.annotation.Annotation is the super-interface of all annotations.