This code snippet give us better understanding on Java Annotations usage and their benifits.
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//test class
public class AnontationsExamplesKKC {
public static void main(String args[]) throws Exception {
Class<AnnotatedClass> classObject = AnnotatedClass.class;
readAnnotation(classObject);
Method method1 = classObject.getMethod("annotatedMethod1",
new Class[] {});
readAnnotation(method1);
Method method2 = classObject.getMethod("annotatedMethod2",
new Class[] {});
readAnnotation(method2);
}
//this method to read the annotations of the Annotated class.
static void readAnnotation(AnnotatedElement element) {
try {
System.out.println("nFinding annotations on "
+ element.getClass().getName());
Annotation[] classAnnotations = element.getAnnotations();
for (Annotation annotation : classAnnotations) {
if (annotation instanceof Author) {
Author author = (Author) annotation;
System.out.println("Author name:" + author.name());
} else if (annotation instanceof Version) {
Version version = (Version) annotation;
System.out.println("Version number:" + version.number());
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
@Target(value = { ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface Author {
String name() default "unknown";
}
@Target(value = { ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface Version {
double number();
}
@Author(name = "Sam")
@Version(number = 1.0)
class AnnotatedClass {
@Author(name = "Author1")
@Version(number = 2.0f)
public void annotatedMethod1() {
}
@Author(name = "Author2")
@Version(number = 4.0)
public void annotatedMethod2() {
}
}