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

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

Description

Find a field with the given name on the given class, regardless of if it is declared on the class or on of its superclasses.

License

Open Source License

Declaration

public static Field findField(Class<?> pClass, String fieldName) throws NoSuchFieldException 

Method Source Code


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

import java.lang.reflect.Field;

import java.util.ArrayList;

public class Main {
    /**/*  ww  w  .ja  v a  2  s.c o m*/
     * Find a field with the given name on the given class, regardless of if it is declared on the class or
     * on of its superclasses.
     */
    public static Field findField(Class<?> pClass, String fieldName) throws NoSuchFieldException {
        Field[] fields = getAllFields(pClass);
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].getName().equals(fieldName)) {
                return fields[i];
            }
        }

        throw new NoSuchFieldException(
                "Unable to find field " + fieldName + " on class " + pClass.getCanonicalName());
    }

    /**
     * Get an array of all fields, irrespective of modifier, of a given Class.
     * @param pClass Class to get a field array for.
     * @return An array of Field objects representing every field in the given class.
     */
    public static Field[] getAllFields(Class<?> pClass) {
        ArrayList<Field> fds = new ArrayList<Field>();
        // Collect *all* the fields;
        Class<?> clazz = pClass;
        while (clazz != null) {
            Field[] fs = clazz.getDeclaredFields();
            for (int i = 0; i < fs.length; i++) {
                fds.add(fs[i]);
            }

            clazz = clazz.getSuperclass();
        }

        return fds.toArray(new Field[fds.size()]);
    }
}

Related

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