Wednesday, 13 February 2013

Annotation Processing at Runtime with Reflection

Heres a quick walkthrough on how to create custom annotations, allowing you to add some info to your classes that can be used at runtime.

1. Create an Annotation
First lets define an annotation in Awesome.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME) //keep annotation info for runtime
@Target({ElementType.FIELD, ElementType.METHOD}) //annotation can be placed on a fiels or method
public @interface Awesome{}

2. Use Annotation
Now Lets define a class that uses the the Awesome Annotation. DetectAwesomeness.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class DetectAwesomeness{
  @Awesome
  private String field1;

  private String field2;

  @Awesome
  private String field3;

  @Awesome
  public void method1(){}

  @Awesome
  public void method2(){}

  public void method3(){}

  public void printAwesomeFieldNames(){
    Class self = this.getClass();
  
    //for each field on this class
    for(Field field : Arrays.asList(self.getDeclaredFields())){
      //if field is annotated with @Awesome
      if(field.isAnnotationPresent(Awesome.class)){
        //print the name of the field
        System.out.println("Awesome Field: "+ field.getName());
      }
    }
  }
  
  public void printAwesomeMethodNames(){
    Class self = this.getClass();
    
    //for each method on this class
    for(Method method : Arrays.asList(self.getDeclaredMethods())){
       //if method is annotated with @Awesome
       if(method.isAnnotationPresent(Awesome.class)){
         System.out.println("Awesome method: "+ method.getName());
       }
    }
  }
 
  //Main method
  public static void main(String [] args){
    //create object of class
    DetectAwesomeness detector = new DetectAwesomeness();
  
    detector.printAwesomeFieldNames();
    detector.printAwesomeMethodNames();
  }
}

3. Run
Running the main method (java DetectAwesomeness) will print the names of fields and methods annotated with @Awesome
Awesome Field: field1
Awesome Field: field3
Awesome method: method1
Awesome method: method2

No comments:

Post a Comment