Get annotation by type in Java

Description

The following code shows how to get annotation by type.

Example


//  w ww .  jav  a 2  s  .co m
import java.lang.annotation.Annotation;


public class Main {

    public static void main(String[] args) throws Exception{
        Annotation[] as = Class.forName("Person").getAnnotations();
        for(int i=0;i<as.length;i++){
            System.out.println(as[i].annotationType());        
        }
        /*Annotation a =Class.forName("Person").getAnnotation(javax.ejb.Entity.class);
        System.out.println(a);  
        Annotation[] das = Class.forName("Person").getDeclaredAnnotations();
        for(int i=0;i<das.length;i++){
            System.out.println(das[i].annotationType());        
        } 
        */       
    }
}

/*
import javax.ejb.Entity;
import javax.ejb.AccessType;
import javax.ejb.Id;
import javax.ejb.GeneratorType;
import java.io.Serializable;

@Entity(access = AccessType.FIELD)
public class Person implements Serializable {
  @Id(generate = GeneratorType.AUTO)
  Integer id;
  String name;
}
*/




















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy