Here you can find the source of findFieldFromClassHierarchy(Class> clazz, String fieldName)
Parameter | Description |
---|---|
clazz | The type of the actual object. |
fieldName | The name of the requested field. |
private static Field findFieldFromClassHierarchy(Class<?> clazz, String fieldName) throws NoSuchFieldException
//package com.java2s; //License from project: Apache License import java.lang.reflect.Field; public class Main { /**//from ww w. j a v a2 s. c om * Finds the requested field from the class hierarchy. * @param clazz The type of the actual object. * @param fieldName The name of the requested field. * @return */ private static Field findFieldFromClassHierarchy(Class<?> clazz, String fieldName) throws NoSuchFieldException { Class<?> current = clazz; //Iterate the class hierarchy from the actual class //to the super class and try to find the requested field. do { try { return current.getDeclaredField(fieldName); } catch (Exception e) { //An exception simply means that field is not found. } } while ((current = current.getSuperclass()) != null); //This signals that the requested field is not found. throw new NoSuchFieldException(String.format("No field found with the field name %s", fieldName)); } }