Here you can find the source of findField(Class clazz, String name)
Parameter | Description |
---|---|
name | The name of the field to be found. |
clazz | The class of the field to be found. |
Parameter | Description |
---|---|
NoSuchFieldException | an exception |
private static Field findField(Class clazz, String name) throws NoSuchFieldException
//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); } }