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

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

Description

Find a field on a class.

License

Open Source License

Parameter

Parameter Description
fieldName The field name to find
cl The class

Return

The field found, null otherwise

Declaration

public static Field findField(String fieldName, Class cl) 

Method Source Code

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

import java.lang.reflect.Field;

public class Main {
    /**//from   w  w w  . j  a va  2s .com
     * Find a field on a class. Do the lookup in the super classes of the
     * current class.
     * 
     * @param fieldName The field name to find
     * @param cl The class
     * @return The field found, null otherwise
     */
    public static Field findField(String fieldName, Class cl) {
        Class scannedClass = cl;

        do {
            try {
                // Retrieve the field for the current level of class and field name
                return scannedClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException | SecurityException e) {
                scannedClass = scannedClass.getSuperclass();
            }
        } while (scannedClass != Object.class);

        return null;
    }
}

Related

  1. findField(Object object, String name, Class klass)
  2. findField(Object propertyId, Class classOfItem)
  3. findField(Object target, Class type)
  4. findField(Object target, String fieldName)
  5. findField(String fieldName, ArrayList fields)
  6. findField(String fieldName, Class type)
  7. findField(String name, Class c)
  8. findField(String name, Object o)
  9. findField(String string, Class clazz)