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

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

Description

find Field

License

Open Source License

Declaration

public static Field findField(Class clazz, String name) 

Method Source Code

//package com.java2s;
/***************************************************************************
 * Copyright (c) 2006 Eike Stepper, Fuggerstr. 39, 10777 Berlin, Germany.
 * 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
 * //from www .ja va 2  s .  c  o  m
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/

import java.lang.reflect.Field;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static Field findField(Class clazz, String name) {
        List<Field> fields = getAllDeclaredFields(clazz);
        for (Field field : fields) {
            if (name.equals(field.getName()))
                return field;
        }

        return null;
    }

    public static List<Field> getAllDeclaredFields(Class clazz) {
        return getAllDeclaredFields(clazz, Object.class);
    }

    public static List<Field> getAllDeclaredFields(Class clazz, Class baseClass) {
        List<Field> result = new ArrayList<Field>();
        collectAllDeclaredFields(clazz, baseClass, result);
        return result;
    }

    private static void collectAllDeclaredFields(Class clazz, Class baseClass, List<Field> result) {
        if (clazz != baseClass) {
            collectAllDeclaredFields(clazz.getSuperclass(), baseClass, result);

            Field[] fields = clazz.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                result.add(fields[i]);
            }
        }
    }
}

Related

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