Find Annotated Fields : Annotation « Reflection « Java






Find Annotated Fields

    
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Util{
  public static Field[] findAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) {
    Field[] declaredFields = clazz.getDeclaredFields();
    List<Field> annotatedFields = new ArrayList<Field>(declaredFields.length);
    for (Field field : declaredFields) {
      if( field.isAnnotationPresent(annotationClass)){
        annotatedFields.add(field);
      }
    }
    return annotatedFields.toArray(new Field[annotatedFields.size()]);    
  }
  
  public static Annotation[] findFieldAnnotations(Class<?> clazz,String fieldName) throws NoSuchFieldException {
    Field field = clazz.getDeclaredField(fieldName);
    return field.getAnnotations();
  }
  
  public static <T extends Annotation> T findFieldAnnotation(Class<?> clazz,String fieldName, Class<T> annotationClass) throws NoSuchFieldException {
    Field field = clazz.getDeclaredField(fieldName);
    return field.getAnnotation(annotationClass);
  }
}

   
    
    
    
  








Related examples in the same category

1.Uses reflection to display the annotation associated with a method.
2.Get annotation by annotation class
3.Show all annotations for a class and a method.
4.default values in an annotation.
5.Does a method have an annotation
6.Get Annotation Parameter
7.A better concise toString method for annotation types
8.Find Annotated Method
9.Get default annotation value
10.Get annotation value
11.Is Field Annotation Present
12.Get Annotated Declared Fields