I\'m a little confused about the difference between the getFields
method and the getDeclaredFields
method when using Java reflection.
I re
As already mentioned, Class.getDeclaredField(String)
only looks at the fields from the Class
in which you call it.
If you want to search a Field
in the Class
hierarchy, you can use this simple function:
/**
* Returns the first {@link Field} in the hierarchy for the specified name
*/
public static Field getField(Class> clazz, String name) {
Field field = null;
while (clazz != null && field == null) {
try {
field = clazz.getDeclaredField(name);
} catch (Exception e) {
}
clazz = clazz.getSuperclass();
}
return field;
}
This is useful to find a private
field from a superclass, for example. Also, if you want to modify its value, you can use it like this:
/**
* Sets {@code value} to the first {@link Field} in the {@code object} hierarchy, for the specified name
*/
public static void setField(Object object, String fieldName, Object value) throws Exception {
Field field = getField(object.getClass(), fieldName);
field.setAccessible(true);
field.set(object, value);
}