Java Reflection Field Find findField(Class clazz, String name)

Here you can find the source of findField(Class clazz, String name)

Description

Finds a field of a given class recursively by stepping up the inheritance chain.

License

Open Source License

Parameter

Parameter Description
name The name of the field to be found.
clazz The class of the field to be found.

Exception

Parameter Description
NoSuchFieldException an exception

Return

The Field.

Declaration

private static Field findField(Class clazz, String name) throws NoSuchFieldException 

Method Source Code


//package com.java2s;
/*/*from w  w w . jav  a 2 s.c om*/
 * Copyright 2017, Leanplum, Inc. All rights reserved.
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.lang.reflect.Field;

public class Main {
    /**
     * Finds a field of a given class recursively by stepping up the inheritance chain. This method
     * also finds private fields, for public methods use: clazz.getField().
     *
     * @param name The name of the field to be found.
     * @param clazz The class of the field to be found.
     * @return The Field.
     * @throws NoSuchFieldException
     */
    private static Field findField(Class clazz, String name) throws NoSuchFieldException {
        Class currentClass = clazz;
        while (currentClass != Object.class) {
            for (Field field : currentClass.getDeclaredFields()) {
                if (name.equals(field.getName())) {
                    return field;
                }
            }
            currentClass = currentClass.getSuperclass();
        }
        throw new NoSuchFieldException("Field " + name + " not found for class " + clazz);
    }
}

Related

  1. findField(Class classType, String fieldName, Class fieldType)
  2. findField(Class clazz, Class type, String name)
  3. findField(Class clazz, String fieldName)
  4. findField(Class clazz, String fieldName)
  5. findField(Class clazz, String name)
  6. findField(Class clazz, String name)
  7. findField(Class clazz, String name)
  8. findField(Class cls, String name)
  9. findField(Class objectClass, String fieldName)