Java Reflection Field Find findField(Class type, Class annotationClass)

Here you can find the source of findField(Class type, Class annotationClass)

Description

find Field

License

Open Source License

Declaration

public static <T extends Annotation> Field findField(Class<?> type, Class<T> annotationClass) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    private static Map<String, Field> neverExpiredFieldObject = new ConcurrentHashMap<>();

    public static <T extends Annotation> Field findField(Class<?> type, Class<T> annotationClass) throws Exception {
        String classKey = "$Utility$findField".concat(type.getName()).concat(annotationClass.getName());
        if (!neverExpiredFieldObject.containsKey(classKey)) {
            neverExpiredFieldObject.put(classKey, findFieldEx(type, annotationClass));
        }//from w ww .j  a v a2 s. co  m
        return neverExpiredFieldObject.get(classKey);
    }

    private static <T extends Annotation> Field findFieldEx(Class<?> type, Class<T> annotationClass) {
        for (Field field : type.getDeclaredFields()) {
            if (field.getAnnotation(annotationClass) != null) {
                return field;
            }
        }
        throw new IllegalArgumentException("Specific ".concat(type.getName()).concat(" must have annotation ")
                .concat(annotationClass.getName()));
    }
}

Related

  1. findField(Class currentClass, String fieldName)
  2. findField(Class inClass, String fieldName)
  3. findField(Class klass, String name)
  4. findField(Class pClass, String fieldName)
  5. findField(Class targetClass, String fieldName)
  6. findField(Class type, String fieldName)
  7. findField(final Class aClass, final String fieldName)
  8. findField(final Class clazz, final String name)
  9. findField(final Class clazz, final String name)