Tuesday, 24 November 2015

Java Annotations Tutorial and Example

What is Java Annotations & How to Create It?

Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection.

Classes, methods, variables, parameters and packages may be annotated. 

Some Built-in Java Annotations

  • @Override - Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces.
  • @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
  • @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.

Java Annotation Types

  1. Build-time instruction (Development time) - Retention is set to source only, such annotation are use full at source level only and removed by compiler while generating binary class file.
    e.g. @Documented
  2. Compiler  instructions (Deployment time) - Retention is set be to class only. Such annotation are used by compiler or deployment tools for taking some specific action e.g. producing compile time error in case of some rule or guideline violation.
    e.g. @Depricated, @Override
  3. Runtime instructions (Execution time) - Retention is set run-time, such annotation are retained in class file are used for deducing some meta information at run time and may effect run time processing. These annotations are not ignored by VM.
    e.g. @Entity, @Test

Use cases

Annotations can be used for many different purposes, the most common ones are:
  • Information for the compiler - Annotations can be used by the compiler to produce warnings or even errors based on different rules. One example of this kind of usage is the Java 8 @FunctionalInterface annotation. This one makes the compiler to validate the annotated class and check if it is a correct functional interface or not.
  • Documentation - Annotations can be used by software applications to measure the quality of the code like FindBugs or PMD do or generate reports automatically like Jenkins, Jira or Teamcity.
  • Code generation - annotations can be used to generate code or XML files automatically using metadata information present in the code. A good example of this is the JAXB library.
  • Runtime processing - Annotations that are examined in runtime can be used for different objectives like unit testing (Junit), dependency injection (Spring), validation, logging (Log4J) ,data access (Hibernate) etc.

Creating Custom Annotation

Rules of Thumb for Defining Java Annotation Types

Here are some rules-of-thumb when defining an annotation type:
  1. Annotation declaration should start with an 'at' sign like @, following with an interface keyword, following with the annotation name.
  2. Method declarations should not have any parameters.
  3. Method declarations should not have any throws clauses.
  4. Return types of the method should be one of the following:
    • primitives
    • String
    • Class
    • enum
    • array of the above types

The Java reflection API

  • getAnnotations(): Returns all annotations for the given element, also the ones that are not explicitly defined in the element definition.
  • isAnnotationPresent(annotation): Checks if the passed annotation in available or not in the current element.
  • getAnnotation(class): Retrieves an specific annotation passed as parameter. Returns null if this annotation is not present for the given element.
This class is implementing by java.lang.Classjava.lang.reflect.Method and java.lang.reflect.Field among others, so can be used basically with any kind of Java element.

RetentionPolicy:
 CLASS:Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
 RUNTIME:Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
 SOURCE: Annotations are to be discarded by the compiler.

Create Custom Annotation Example

Define new custom annotation


@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface CustomAnnotationMethod {
public String author() default "danibuiza";
public String date();
public String description();

Use on Class or Method

@CustomAnnotationClass( date = "2014-05-05" )
public class AnnotatedClass {

@CustomAnnotationMethod( date = "2014-06-05", description = "annotated method" )
public String annotatedMethod() {
return "nothing niente";
}
}

Write a program to Process Annotations


public static void main(String[] args) throws Exception {
Class < AnnotatedClass > object = AnnotatedClass.class;
// Retrieve all annotations from the class
Annotation[] annotations = object.getAnnotations();
for (Annotation annotation: annotations) {
System.out.println(annotation);
}

// Checks if an annotation is present
if (object.isAnnotationPresent(CustomAnnotationClass.class)) {
// Gets the desired annotation
Annotation annotation = object.getAnnotation(CustomAnnotationClass.class);
System.out.println(annotation);
}
// the same for all methods of the class
for (Method method: object.getDeclaredMethods()) {
if (method.isAnnotationPresent(CustomAnnotationMethod.class)) {
Annotation annotation = method.getAnnotation(CustomAnnotationMethod.class);
System.out.println(annotation);
}
}
}

No comments:

Post a comment