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

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

Description

Search a java.lang.reflect.Field given its class and name

License

Apache License

Parameter

Parameter Description
clazz a parameter
name a parameter

Declaration

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

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;

public class Main {
    /**//from  ww w . ja va 2 s.  c om
     * Search a {@link java.lang.reflect.Field} given its class and name
     * 
     * @param clazz
     * @param name
     * @return
     */
    public static Field findField(Class<?> clazz, String name) {
        return findField(clazz, name, null);
    }

    /**
     * Search a {@link java.lang.reflect.Field} given its class and name
     * 
     * @param clazz
     * @param name
     * @param type
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static Field findField(Class<?> clazz, String name, Class<?> type) {
        validateField(clazz, name, type);
        Class searchType = clazz;
        while ((!(Object.class.equals(searchType))) && (searchType != null)) {
            Field[] fields = searchType.getDeclaredFields();
            for (Field field : fields) {
                if ((((name == null) || (name.equals(field.getName()))))
                        && (((type == null) || (type.equals(field.getType()))))) {
                    return field;
                }
            }
            searchType = searchType.getSuperclass();
        }
        return null;
    }

    private static void validateField(Class<?> clazz, String name, Class<?> type) {
        if (clazz == null) {
            throw new IllegalArgumentException("Class must not be null");
        }
        if (!((name != null) || (type != null))) {
            throw new IllegalArgumentException("Either name or type of the field must be specified");
        }
    }
}

Related

  1. findField(Class clazz, String name)
  2. findField(Class clazz, String name)
  3. findField(Class clazz, String name)
  4. findField(Class clazz, String name)
  5. findField(Class clazz, String name)
  6. findField(Class clazz, String name)
  7. findField(Class clazz, String propName)
  8. findField(Class clazz, String targetName, Class targetType, boolean checkInheritance, boolean strictType)
  9. findField(Class cls, String fieldName)