Java Reflection Field Find findFieldInClass(Class clazz, String fieldName)

Here you can find the source of findFieldInClass(Class clazz, String fieldName)

Description

find Field In Class

License

Open Source License

Declaration

private static Field findFieldInClass(Class<?> clazz, String fieldName) throws NoSuchFieldException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 Salesforce.com, inc..
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * //www  .  j a  v a 2  s  .  co m
 * Contributors:
 *     Salesforce.com, inc. - initial API and implementation
 ******************************************************************************/

import java.lang.reflect.Field;

public class Main {
    @SuppressWarnings({ "unchecked" })
    public static <T> T findFieldInClass(Object instance, String fieldName) throws NoSuchFieldException {
        Field field = findFieldInClass(instance.getClass(), fieldName);
        field.setAccessible(true);

        try {
            return (T) field.get(instance);
        } catch (IllegalAccessException e) {
            throw new NoSuchFieldException();
        }
    }

    private static Field findFieldInClass(Class<?> clazz, String fieldName) throws NoSuchFieldException {
        try {
            return clazz.getDeclaredField(fieldName);
        }

        catch (NoSuchFieldException e) {
            // if we don't have a superclass, continue
            if (clazz.getSuperclass().equals(Object.class)) {
                throw e;
            }

            // check in the superclass
            return findFieldInClass(clazz.getSuperclass(), fieldName);
        }
    }
}

Related

  1. findFieldByName(Class owner, String name)
  2. findFieldEx(Class type, Class annotationClass)
  3. findFieldFromClassHierarchy(Class clazz, String fieldName)
  4. findFieldFromGetter(Class clazz, Method method)
  5. findFieldIn(Class type, String name)
  6. findFieldInClassHierarchy(Class clazz, String fieldName)
  7. findFieldIncludeSuperclass(String fieldName, Class clazz)
  8. findFieldInternal(Class currentClass, Class annotation, Set fields)
  9. findFieldOfBean(Object bean, String fieldName)