Here you can find the source of findFieldWithAnnotation(String fieldName, Class> clazz, Class extends Annotation> annotationType)
Parameter | Description |
---|---|
fieldName | The field name. |
clazz | The scanned class. |
annotationType | The expected annotation type. |
public static Field findFieldWithAnnotation(String fieldName, Class<?> clazz, Class<? extends Annotation> annotationType)
//package com.java2s; //License from project: LGPL import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { /**// w w w .j a va 2s .c om * Look for a field based on his name and a given Annotation in a class. * * @param fieldName The field name. * @param clazz The scanned class. * @param annotationType The expected annotation type. * @return The field if found, null if not. */ public static Field findFieldWithAnnotation(String fieldName, Class<?> clazz, Class<? extends Annotation> annotationType) { Field field = getField(fieldName, clazz); if (field != null && field.isAnnotationPresent(annotationType)) { return field; } return null; } /** * Find a field with the given name and class annotation * * @param fieldName The field name * @param clazz The annotation class. * @return the field, null if not found. */ public static Field getField(String fieldName, Class<?> clazz) { List<Field> fields = getAllFields(clazz); for (Field field : fields) { if (field.getName().equals(fieldName)) { return field; } } return null; } /** * Return all fields of the class, including inherited one. * * @param clazz The class. * @return The list of all fields. */ public static List<Field> getAllFields(Class<?> clazz) { List<Field> currentClassFields = new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())); Class<?> parentClass = clazz.getSuperclass(); if (parentClass != null && !(parentClass.equals(Object.class))) { List<Field> parentClassFields = getAllFields(parentClass); currentClassFields.addAll(parentClassFields); } return currentClassFields; } }