Annotations

Annotations provide actionable information to the compiler, the runtime engine and other processing tools.

They are not part of the program in the sense that they do not modify the code at all.

What annotations can do

  • provide additional information to the compiler to detect errors or suppress warnings
  • provide information to the tools to generate code
  • provide processing information to the runtime, like to plug in objects

For example, the derived class may override a method in the base class. If the method is decorated with the annotation @Override, the compiler can check for errors in the method signature.

@SuppressWarnings may be used to, well, suppress compiler warnings.

@Deprecated is used to inform the user that the method should no longer be used since it has been superceded.

Java frameworks such as Spring may load classes at runtime based on the annotations​ specified.

A class, a method or a variable may be decorated with one or more annotations.

Annotations can be easily identified by the symbol @ followed by the name of the entity.

Annotations contain elements that may be declared with or without default values.

An example

Annotations are defined much like interfaces.

@interface Signature {
    String director();
    int version() default 1;
    String movie() default "...";
    String[] actors()
}

Usage:


@Signature (
    director = "anand",
    version = 1.1,
    movie = "homies"
    actors = {"Akhil","Nikhil",")
public class HomeProductions {

}

Annotations can be annotated by other annotations.

For example, the above annotation may be added to javadoc-generated documentation by specifying @Documented in its definition.

Using @Retention, it can also be specified whether the annotation is meant to be used at the source level, at compile time or the runtime.

@Target specifies whether the annotation is to be applied for the class, the method or the variable.

Annotations can be inherited from other annotations, using @Inherited.

@Repeatable allows the annotation to be applied to the same entity more than once.

Re-writing the annotation definition above:

@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@interface Signature {
    String director();
    int version() default 1;
    String movie() default "...";
    String[] actors()
}
Advertisements

Author: Anand Betanabhotla

Corporate Trainer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s