Java Reflection Field Find findFieldFromClassHierarchy(Class clazz, String fieldName)

Here you can find the source of findFieldFromClassHierarchy(Class clazz, String fieldName)

Description

Finds the requested field from the class hierarchy.

License

Apache License

Parameter

Parameter Description
clazz The type of the actual object.
fieldName The name of the requested field.

Declaration

private static Field findFieldFromClassHierarchy(Class<?> clazz, String fieldName) throws NoSuchFieldException 

Method Source Code


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

import java.lang.reflect.Field;

public class Main {
    /**//from  ww w. j a v  a2  s. c  om
     * Finds the requested field from the class hierarchy.
     * @param clazz     The type of the actual object.
     * @param fieldName The name of the requested field.
     * @return
     */
    private static Field findFieldFromClassHierarchy(Class<?> clazz, String fieldName) throws NoSuchFieldException {
        Class<?> current = clazz;

        //Iterate the class hierarchy from the actual class
        //to the super class and try to find the requested field.
        do {
            try {
                return current.getDeclaredField(fieldName);
            } catch (Exception e) {
                //An exception simply means that field is not found.
            }
        } while ((current = current.getSuperclass()) != null);

        //This signals that the requested field is not found.
        throw new NoSuchFieldException(String.format("No field found with the field name %s", fieldName));
    }
}

Related

  1. findField(String name, Object o)
  2. findField(String string, Class clazz)
  3. findField0(Class clazz, String name, String methodName)
  4. findFieldByName(Class owner, String name)
  5. findFieldEx(Class type, Class annotationClass)
  6. findFieldFromGetter(Class clazz, Method method)
  7. findFieldIn(Class type, String name)
  8. findFieldInClass(Class clazz, String fieldName)
  9. findFieldInClassHierarchy(Class clazz, String fieldName)