Java examples for java.lang.annotation:Field Annotation
find Field Annotation By Annotation Class
//package com.java2s; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] argv) throws Exception { Class clazz = String.class; String fieldName = "java2s.com"; Class annotationClass = String.class; System.out.println(java.util.Arrays .toString(findFieldAnnotationByAnnotationClass(clazz, fieldName, annotationClass))); }/*from w w w . j av a2 s .c om*/ public static Object[] findFieldAnnotationByAnnotationClass( Class<?> clazz, String fieldName, Class<? extends Annotation> annotationClass) { Annotation[] allAnnotations = findFieldAnnotation(clazz, fieldName); ArrayList<Annotation> annotations = new ArrayList<Annotation>(); if (allAnnotations != null) { for (int i = 0; i < allAnnotations.length; i++) { Annotation annotation = allAnnotations[i]; if (annotation.annotationType().equals(annotationClass)) { annotations.add(annotation); } } return annotations.toArray(); } else { return null; } } public static Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) { Annotation[] annotations = null; try { List<Field> fields = getAllFields(clazz); Field field = null; for (Field fld : fields) { if (fld.getName().equals(fieldName)) { field = fld; break; } } if (field != null) { annotations = field.getAnnotations(); } } catch (SecurityException e) { } return annotations; } public static List<Field> getAllFields(Class<?> type) { return getAllFields(null, type); } private static List<Field> getAllFields(List<Field> fields, Class<?> type) { if (fields == null) fields = new ArrayList<Field>(); for (Field field : type.getDeclaredFields()) { fields.add(field); } if (type.getSuperclass() != null) { fields = getAllFields(fields, type.getSuperclass()); } return fields; } }