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

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

Description

Get the field related to a name

License

Open Source License

Parameter

Parameter Description
aClass The class to search for the field
fieldName the field to search for

Return

the field related to a name in the class

Declaration

public static Object findField(final Class<?> aClass,
        final String fieldName) 

Method Source Code

//package com.java2s;
/**//from  w  ww  . j a v a 2 s  .c o  m
 * TestHelper.java
 * Copyright 2005 (c) Andrew Wilson <nuance@sourceforge.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Current Version: $Revision$
 *
 */

import java.lang.reflect.Field;

import java.util.Arrays;

public class Main {
    /**
     * Get the field related to a name
     * @param aClass The class to search for the field
     * @param fieldName the field to search for
     * @return the field related to a name in the class
     */
    public static Object findField(final Class<?> aClass,
            final String fieldName) {
        try {
            Class<?> clazz = aClass;
            while (true) {
                for (final Field f : Arrays.asList(clazz
                        .getDeclaredFields())) {
                    if (f.getName().equals(fieldName)) {
                        f.setAccessible(true);
                        return f;
                    }
                }
                if (!"Object".equals(clazz.getName())) {
                    clazz = clazz.getSuperclass();
                } else {
                    break;
                }
            }

        } catch (SecurityException e) {
            System.out.println(e);
        }
        return null;
    }
}

Related

  1. findField(Class klass, String name)
  2. findField(Class pClass, String fieldName)
  3. findField(Class targetClass, String fieldName)
  4. findField(Class type, Class annotationClass)
  5. findField(Class type, String fieldName)
  6. findField(final Class clazz, final String name)
  7. findField(final Class clazz, final String name)
  8. findField(final Class clazz, final String name, final Class type)
  9. findField(final Class cls, final String fieldName)