Java examples for java.lang.annotation:Field Annotation
Takes the Class finds the specified field and returns the annotation other wise returns null
//package com.java2s; import java.lang.annotation.Annotation; import java.lang.reflect.Field; public class Main { public static void main(String[] argv) throws Exception { Class clazz = String.class; String field = "java2s.com"; Class annotationClass = String.class; System.out.println(getAnnotationForFieldofClass(clazz, field, annotationClass));/*from w ww.j a v a2s .c o m*/ } /** * Takes the Class finds the specified field and returns the annotation * other wise returns null * * @param clazz * @param field * @param annotationClass * @return */ public static Annotation getAnnotationForFieldofClass(Class clazz, String field, Class annotationClass) { String s = ""; Field[] fields = clazz.getDeclaredFields(); Annotation annotation; for (Field f : fields) { String theField = f.toString(); if (field.equalsIgnoreCase(theField.substring(theField .lastIndexOf(".") + 1))) { annotation = f.getAnnotation(annotationClass); if (annotation != null) { return annotation; } } } return null; } }