Search superclasses to find declared fields
@@ -14,14 +14,16 @@ public final class ReflectionUtils {
private ReflectionUtils() {
}
- public static <T> T getClassProperty(Class clazz, Object invoker, String property, Class<? extends T> castTo) throws NoSuchFieldException, IllegalAccessException {
- Field field = clazz.getDeclaredField(property);
+ public static <T> T getClassProperty(Class clazz, Object invoker, String property, Class<? extends T> castTo)
+ throws NoSuchFieldException, IllegalAccessException {
+ Field field = getClassField(clazz, property);
field.setAccessible(true);
return (T) field.get(invoker);
}
- public static void setClassProperty(Class clazz, Object invoker, String property, Object value) throws NoSuchFieldException, IllegalAccessException {
- Field field = clazz.getDeclaredField(property);
+ public static void setClassProperty(Class clazz, Object invoker, String property, Object value)
+ throws NoSuchFieldException, IllegalAccessException {
+ Field field = getClassField(clazz, property);
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
@@ -29,9 +31,27 @@ public final class ReflectionUtils {
field.set(invoker, value);
}
- public static <T> Constructor<T> getConstructor(Class clazz, Class<?>... parameterTypes) throws NoSuchMethodException {
+ public static <T> Constructor<T> getConstructor(Class clazz, Class<?>... parameterTypes)
+ throws NoSuchMethodException {
Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
constructor.setAccessible(true);
return constructor;
}
+
+ private static Field getClassField(Class clazz, String property) throws NoSuchFieldException {
+ Field field = null;
+ while (field == null) {
+ try {
+ field = clazz.getDeclaredField(property);
+ break;
+ } catch (NoSuchFieldException e) {
+ clazz = clazz.getSuperclass();
+ // No more superclasses
+ if (clazz == null) {
+ throw e;
+ }
+ }
+ }
+ return field;
+ }
}
