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

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

Description

Find the field with the given name in the class.

License

Open Source License

Parameter

Parameter Description
type Class in which to search for the given field.
fieldName Name of the field for which to search.

Return

The field, or null if no such field exists.

Declaration

public static Field findField(Class type, String fieldName) 

Method Source Code

//package com.java2s;
/*// w w w . j  ava 2  s.  co m
* Copyright 2012-2016 Broad Institute, Inc.
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import java.lang.reflect.*;

public class Main {
    /**
     * Find the field with the given name in the class.  Will inspect all fields, independent
     * of access level.
     * @param type Class in which to search for the given field.
     * @param fieldName Name of the field for which to search.
     * @return The field, or null if no such field exists.
     */
    public static Field findField(Class type, String fieldName) {
        while (type != null) {
            Field[] fields = type.getDeclaredFields();
            for (Field field : fields) {
                if (field.getName().equals(fieldName))
                    return field;
            }
            type = type.getSuperclass();
        }
        return null;
    }
}

Related

  1. findField(Class clazz, String name)
  2. findField(Class clazz, String name)
  3. findField(Class clazz, String name)
  4. findField(Class cls, String name)
  5. findField(Class objectClass, String fieldName)
  6. findField(Class c, String name)
  7. findField(Class c, String property, Class propertyType)
  8. findField(Class cl, String fieldName)
  9. findField(Class classToCheck, String propertyName)