Annotations in Java
Annotations in Java, provide a mean to describe classes, fields and methods. Essentially, they are a form of metadata added to a Java source file, they can’t affect the semantics of a program directly. However, annotations can be read at run-time using Reflection & this process is known as Introspection. Then it could be used to modify classes, fields or methods.
This feature, is often exploited by Libraries & SDKs (hibernate, JUnit, Spring Framework) to simplify or reduce the amount of code that a programmer would unless do in order to work with these Libraries or SDKs.Therefore, it’s fair to say Annotations and Reflection work hand-in hand in Java.
We also get to limit the availability of an annotation to either compile-time or runtime. Below is a simple example on creating a custom annotation
01. Driver.java
package io.hamzeen;import java.lang.annotation.Annotation;public class Driver { public static void main(String[] args) {
Class<TestAlpha> obj = TestAlpha.class;
if (obj.isAnnotationPresent(IssueInfo.class)) { Annotation annotation = obj.getAnnotation(IssueInfo.class);
IssueInfo testerInfo = (IssueInfo) annotation; System.out.printf("%nType: %s", testerInfo.type());
System.out.printf("%nReporter: %s", testerInfo.reporter());
System.out.printf("%nCreated On: %s%n%n",
testerInfo.created());
}
}
}
02. TestAlpha.java
package io.hamzeen;import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {}
03. IssueInfo.java
package io.hamzeen;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/**
* @author Hamzeen. H.
* @created 10/01/2015
*
* IssueInfo annotation definition
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo { public enum Type {
BUG, IMPROVEMENT, FEATURE
} Type type() default Type.BUG; String reporter() default "Vimesh"; String created() default "10/01/2015";
}
P.S. This post is based on my stack-overflow answer at, http://stackoverflow.com/questions/1372876/how-and-where-are-annotations-used-in-java/32903945#32903945
