Java Reflection Field Find findField(Class clazz, final String field)

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

Description

Finds a field by name.

License

Open Source License

Parameter

Parameter Description
clazz the class to search in
field the field to search for

Return

the field or null if not found

Declaration

public static Field findField(Class<?> clazz, final String field) 

Method Source Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    /**/*from   w w w .ja v a 2  s . c o m*/
     * Finds a field by name. The search is performed up the class hierarchy and includes all public, protected,
     * default (package) and private fields which include both static and instance members.  
     *
     * @param clazz the class to search in
     * @param field the field to search for
     * @return the field or null if not found
     */
    public static Field findField(Class<?> clazz, final String field) {
        do {
            for (Field f : clazz.getDeclaredFields()) {
                if (f.getName().equals(field)) {
                    return f;
                }
            }
        } while ((clazz = clazz.getSuperclass()) != null);
        return null;
    }

    /**
     * Finds a field by name and type. The search is performed up the class hierarchy and includes all public,
     * protected, default (package) and private fields which include both static and instance members.
     *
     * @param clazz the class to search in
     * @param field te field to search for
     * @param type the type of the field
     * @return the field or null if not found
     */
    public static Field findField(Class<?> clazz, final String field, final Class<?> type) {
        do {
            for (Field f : clazz.getDeclaredFields()) {
                if (f.getName().equals(field) && f.getType().equals(type)) {
                    return f;
                }
            }
        } while ((clazz = clazz.getSuperclass()) != null);
        return null;
    }
}

Related

  1. findField(Class c, String name)
  2. findField(Class c, String property, Class propertyType)
  3. findField(Class cl, String fieldName)
  4. findField(Class classToCheck, String propertyName)
  5. findField(Class claz, String... names)
  6. findField(Class clazz, String field)
  7. findField(Class clazz, String field, Class type, int index)
  8. findField(Class clazz, String fieldName)
  9. findField(Class clazz, String fieldName)