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

Apache License

Declaration

public static Field findField(Class clazz, String name) 

Method Source Code


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

import java.lang.reflect.*;

import java.util.Objects;

public class Main {
    public static Field findField(Class clazz, String name) {
        return findField(clazz, name, (Class) null);
    }/* w  w  w .j  a  v a2 s  .co m*/

    public static Field findField(Class clazz, String name, Class type) {
        assert Objects.nonNull(clazz);
        assert (name != null || type != null);
        //        Assert.notNull(clazz, "Class must not be null");
        //        Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified");

        for (Class searchType = clazz; !Object.class.equals(searchType)
                && searchType != null; searchType = searchType.getSuperclass()) {
            Field[] fields = searchType.getDeclaredFields();

            for (int i = 0; i < fields.length; ++i) {
                Field field = fields[i];
                if ((name == null || name.equals(field.getName()))
                        && (type == null || type.equals(field.getType()))) {
                    return field;
                }
            }
        }

        return null;
    }
}

Related

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