Java Reflection Field Find findField(Object instance, String name)

Here you can find the source of findField(Object instance, String name)

Description

Locates a given field anywhere in the class inheritance hierarchy.

License

Apache License

Parameter

Parameter Description
instance an object to search the field into.
name field name

Exception

Parameter Description
NoSuchFieldException if the field cannot be located

Return

a field object

Declaration

public static Field findField(Object instance, String name) throws NoSuchFieldException 

Method Source Code


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

import java.lang.reflect.Field;

public class Main {
    /**//from   w  w w . j av a 2s  .  c  o  m
     * Locates a given field anywhere in the class inheritance hierarchy.
     *
     * @param instance an object to search the field into.
     * @param name     field name
     * @return a field object
     * @throws NoSuchFieldException if the field cannot be located
     */
    public static Field findField(Object instance, String name) throws NoSuchFieldException {
        for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
            try {
                Field field = clazz.getDeclaredField(name);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                return field;
            } catch (NoSuchFieldException e) {
                // ignore and search next
            }
        }
        throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
    }
}

Related

  1. findField(final Class klaz, final String fieldName)
  2. findField(final Object instance, final String name)
  3. findField(final Object src, final String fieldName)
  4. findField(final String className, final String fieldName)
  5. findField(Object container, String memberName)
  6. findField(Object obj, String beanPath)
  7. findField(Object obj, String fieldName)
  8. findField(Object obj, String fieldName, Class type)
  9. findField(Object obj, String name)