Wednesday, May 15, 2013

Class Level Custom annotation java example

Create custom annotaion class

package com.arvind;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(value=RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
 String[] customValues();
}
Create Test class for testing
package com.arvind;

import java.lang.reflect.Method;

@CustomAnnotation(customValues = { "First Value", "Second Value" })
public class Test {
 public static void main(String[] args) {
  Test t = new Test();
  boolean present = t.getClass().isAnnotationPresent(CustomAnnotation.class);
  if (present) {
   CustomAnnotation ca = t.getClass().getAnnotation(CustomAnnotation.class);
   if (ca != null) {
    for (String value : ca.customValues()) {
     System.out.println(value);
    }
   }
  }
 }
}

Output will be
First Value
Second Value

No comments:

Post a Comment