Java Reflection Field Find findField(Class inClass, String fieldName)

Here you can find the source of findField(Class inClass, String fieldName)

Description

Finds a field by name within the given class and its super-classes.
Provides private fields too.

License

Open Source License

Parameter

Parameter Description
inClass The class to check for the field.
fieldName Name of the field to find.

Return

The found field or null if not found.

Declaration

public static Field findField(Class<?> inClass, String fieldName) 

Method Source Code

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

import java.lang.reflect.Field;

public class Main {
    /**//from   w  w  w  . jav a2  s. c  om
     * Finds a field by name within the given class and its super-classes.<br>
     * Provides private fields too.
     *
     * @param inClass
     *          The class to check for the field.
     * @param fieldName
     *          Name of the field to find.
     * @return The found field or <code>null</code> if not found.
     */
    public static Field findField(Class<?> inClass, String fieldName) {
        Class<?> c = inClass;
        while (c != null) {
            try {
                return inClass.getDeclaredField(fieldName);
            } catch (SecurityException e) {
                throw new RuntimeException(
                        "Security does not allow to access field '" + fieldName + "' of class " + c, e);
            } catch (NoSuchFieldException e) {
                // Ok. Not declared by the checked class.
            }
            c = c.getSuperclass();
        }
        // not found
        return null;
    }
}

Related

  1. findField(Class clazz, String targetName, Class targetType, boolean checkInheritance, boolean strictType)
  2. findField(Class cls, String fieldName)
  3. findField(Class cls, String fieldName)
  4. findField(Class cls, String fieldName)
  5. findField(Class currentClass, String fieldName)
  6. findField(Class klass, String name)
  7. findField(Class pClass, String fieldName)
  8. findField(Class targetClass, String fieldName)
  9. findField(Class type, Class annotationClass)