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

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

Description

Get the Field-Object for a Field specified by name.
For retrieving the Field this method recursively scans super-Classes as well.

License

Open Source License

Parameter

Parameter Description
cls - the Class that contains the Field
fieldName - the name of the Field

Exception

Parameter Description
NoSuchFieldException - if no matching Field could be found

Return

the Field-Object

Declaration

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

Method Source Code

//package com.java2s;
/**//from   w ww  . java2s.  c  o  m
 * Syncnapsis Framework - Copyright (c) 2012-2014 ultimate
 * This program is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either version
 * 3 of the License, or any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Plublic License along with this program;
 * if not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.Field;

public class Main {
    /**
     * Get the Field-Object for a Field specified by name.<br>
     * For retrieving the Field this method recursively scans super-Classes as well.
     * 
     * @param cls - the Class that contains the Field
     * @param fieldName - the name of the Field
     * @return the Field-Object
     * @throws NoSuchFieldException - if no matching Field could be found
     */
    public static Field findField(Class<?> cls, String fieldName) throws NoSuchFieldException {
        Field field = null;
        while (field == null) {
            try {
                field = cls.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                cls = cls.getSuperclass();
                if (cls.equals(Object.class))
                    throw e;
            }
        }
        return field;
    }
}

Related

  1. findField(Class clazz, String name)
  2. findField(Class clazz, String name)
  3. findField(Class clazz, String name)
  4. findField(Class clazz, String propName)
  5. findField(Class clazz, String targetName, Class targetType, boolean checkInheritance, boolean strictType)
  6. findField(Class cls, String fieldName)
  7. findField(Class cls, String fieldName)
  8. findField(Class currentClass, String fieldName)
  9. findField(Class inClass, String fieldName)