Java Reflection Field Find findField(Class clazz, String name)

Here you can find the source of findField(Class clazz, String name)

Description

find Field

License

Apache License

Declaration

public static Field findField(Class<?> clazz, String name) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    private static final Map<Class<?>, Field[]> declaredFieldsCache = new ConcurrentHashMap<Class<?>, Field[]>(256);

    public static Field findField(Class<?> clazz, String name) {
        return findField(clazz, name, null);
    }//w  w w. j a  v a2 s  .c  om

    public static Field findField(Class<?> clazz, Class<?> type) {
        return findField(clazz, null, type);
    }

    public static Field findField(Class<?> clazz, String name, Class<?> type) {
        if (clazz == null || (name == null && type == null)) {
            return null;
        }
        Class<?> searchType = clazz;
        while (!Object.class.equals(searchType) && searchType != null) {
            Field[] fields = getDeclaredFields(searchType);
            for (Field field : fields) {
                if ((name == null || name.equals(field.getName()))
                        && (type == null || type.equals(field.getType()))) {
                    return field;
                }
            }
            searchType = searchType.getSuperclass();
        }
        return null;
    }

    private static Field[] getDeclaredFields(Class<?> clazz) {
        Field[] result = declaredFieldsCache.get(clazz);
        if (result == null) {
            result = clazz.getDeclaredFields();
            declaredFieldsCache.put(clazz, result);
        }
        return result;
    }
}

Related

  1. findField(Class clazz, String fieldName)
  2. findField(Class clazz, String fname, boolean isSearchSuperclass)
  3. findField(Class clazz, String name)
  4. findField(Class clazz, String name)
  5. findField(Class clazz, String name)
  6. findField(Class clazz, String name)
  7. findField(Class clazz, String name)
  8. findField(Class clazz, String name)
  9. findField(Class clazz, String name)