Here you can find the source of findField(Object instance, String name)
Parameter | Description |
---|---|
instance | an object to search the field into. |
name | field name |
Parameter | Description |
---|---|
NoSuchFieldException | if the field cannot be located |
public static Field findField(Object instance, String name) throws NoSuchFieldException
//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()); } }