ReflectionUtils { public static Field getField(Class<?> clazz, String fieldName) throws NoSuchFieldException { Field resultField = null; Class<?> targetClass = clazz; while (targetClass != null) { try { resultField = targetClass.getDeclaredField(fieldName); break; } catch (NoSuchFieldException e) { targetClass = targetClass.getSuperclass(); } } if (resultField == null) { throw new NoSuchFieldException(String.format("No field named [%s] in class [%s] or superclasses", fieldName, clazz == null ? null : clazz.getName())); } return resultField; } private  ReflectionUtils(); static Collection<Field> getAllFields(Class<?> clazz); static Field getField(Class<?> clazz, String fieldName); static Class getTypeClass(Type type); static void setFieldValue(Object instanceContainingField, String fieldName, Object fieldValue); static Class<?> getLastGenericFieldType(Field field); static Type getLastFieldGenericArgument(Field field); static Type getLastTypeGenericArgument(Type type); static Class<?> getLastGenericClassType(Class clazz, Class filterClass); static Type getGenericClassType(Class clazz, Class filterClass); static Type[] resolveSuperArguments(Type[] parameters, Type childType); static Type[] resolveSuperArguments(Type[] parameters, Class childClass, Type[] childParameters); static Type resolveType(Type type, Map<TypeVariable, Type> typeMapping); static Type resolveType(Type targetType, Type rootType); static Type unserializeType(String serializedType, ClassLoader classLoader); static T getDirectAnnotation(Class<T> annotationClass, AnnotatedElement element); static List<Type> getDirectTypes(Type type); @Unstable static String serializeType(Type type); @Unstable static Collection<Method> getAllMethods(Class<?> clazz);  }
@Test void getField() throws Exception { Field field = ReflectionUtils.getField(TestFieldClass.class, "field"); assertNotNull(field); assertEquals("field", field.getName()); }
@Test void getFieldFromSuperClass() throws Exception { Field field = ReflectionUtils.getField(TestFieldClass.class, "superField"); assertNotNull(field); assertEquals("superField", field.getName()); }
@Test void getFieldWhenDoesntExist() { Throwable exception = assertThrows(NoSuchFieldException.class, () -> { ReflectionUtils.getField(TestFieldClass.class, "doesntexist"); }); assertEquals("No field named [doesntexist] in class [" + TestFieldClass.class.getName() + "] or superclasses", exception.getMessage()); }