How do I create a simple annotation?

Category: java.lang.annotation, viewed: 4355 time(s).

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 org.kodejava.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.

Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats