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

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

Description

This method will find a java Field for with a particular name.

License

Open Source License

Parameter

Parameter Description
cls the java Class to search.
fieldName the name of the field to find.

Return

the java field.

Declaration

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

Method Source Code

//package com.java2s;
/*/*ww  w .  ja v a 2s .  co  m*/
 * Copyright 2015-2018 Ping Identity Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License (GPLv2 only)
 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY 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 Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 */

import java.lang.reflect.Field;

public class Main {
    /**
     * This method will find a java Field for with a particular name.  If
     * needed, this method will search through super classes.  The field
     * does not need to be public.
     *
     * @param cls the java Class to search.
     * @param fieldName the name of the field to find.
     * @return the java field.
     */
    public static Field findField(final Class<?> cls, final String fieldName) {
        Class<?> currentClass = cls;
        while (currentClass != null) {
            Field[] fields = currentClass.getDeclaredFields();
            for (Field field : fields) {
                if (field.getName().equals(fieldName)) {
                    return field;
                }
            }
            currentClass = currentClass.getSuperclass();
        }

        return null;
    }
}

Related

  1. findField(Class type, String fieldName)
  2. findField(final Class aClass, final String fieldName)
  3. findField(final Class clazz, final String name)
  4. findField(final Class clazz, final String name)
  5. findField(final Class clazz, final String name, final Class type)
  6. findField(final Class currentClass, final String fieldName)
  7. findField(final Class declaringClass, final String fieldName)
  8. findField(final Class klaz, final String fieldName)
  9. findField(final Object instance, final String name)