循环向上转型, 获取对象的 DeclaredField

@param object    : 子类对象
@param fieldName : 父类中的属性名
@return 父类中的属性对象
776109
public static Field getDeclaredField(Object object, String fieldName) {
        Field field = null;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                return field;
            } catch (Exception e) {
                //这里甚么都不要做！并且这里的异常必须这样写，不能抛出去。
                //如果这里的异常打印或者往外抛，则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
            }
        }
        return null;
    }
940353
@SuppressWarnings("null")
    // TODO: Too much code, improve this, possibly by breaking it
    public static final Object getObject(Object obj, String fieldName)
    {
        Field embeddedField;
        try
        {
            embeddedField = obj.getClass().getDeclaredField(fieldName);
            if (embeddedField != null)
            {
                if (!embeddedField.isAccessible())
                {
                    embeddedField.setAccessible(true);
                }
                Object embededObject = embeddedField.get(obj);
                if (embededObject == null)
                {
                    Class embeddedObjectClass = embeddedField.getType();
                    if (Collection.class.isAssignableFrom(embeddedObjectClass))
                    {
                        if (embeddedObjectClass.equals(List.class))
                        {
                            return new ArrayList();
                        }
                        else if (embeddedObjectClass.equals(Set.class))
                        {
                            return new HashSet();
                        }
                    }
                    else
                    {
                        embededObject = embeddedField.getType().newInstance();
                        embeddedField.set(obj, embededObject);
                    }

                }
                return embededObject;
            }
            else
            {
                throw new PropertyAccessException("Embedded object not found: " + fieldName);
            }

        }
        catch (Exception e)
        {
            throw new PropertyAccessException(e);
        }
    }
862342
public static Object getFieldValue(String qualifiedFieldName) {
		Class clazz;
		try {
			clazz = classForName(ClassUtils.qualifier(qualifiedFieldName));
		}
		catch (ClassNotFoundException cnfe) {
			return null;
		}
		try {
			return clazz.getField(ClassUtils.unqualify(qualifiedFieldName)).get(null);
		}
		catch (Exception e) {
			return null;
		}
	}
161992
public static Object getFieldValue(Object obj, String fieldName) throws UtilException {
		if (null == obj || StrUtil.isBlank(fieldName)) {
			return null;
		}
		return getFieldValue(obj, getField(obj.getClass(), fieldName));
	}
1123855
def get_declared_fields(mcs, klass, *args, **kwargs):
        
        declared_fields = kwargs.get('dict_class', dict)()
        # Generate the fields provided through inheritance
        opts = klass.opts
        model = getattr(opts, 'model', None)
        if model:
            converter = opts.model_converter()
            declared_fields.update(converter.fields_for_model(
                model,
                fields=opts.fields
            ))
        # Generate the fields provided in the current class
        base_fields = super(SchemaMeta, mcs).get_declared_fields(
            klass, *args, **kwargs
        )
        declared_fields.update(base_fields)
        # Customize fields with provided kwargs
        for field_name, field_kwargs in klass.opts.model_fields_kwargs.items():
            field = declared_fields.get(field_name, None)
            if field:
                # Copy to prevent alteration of a possible parent class's field
                field = copy.copy(field)
                for key, value in field_kwargs.items():
                    setattr(field, key, value)
                declared_fields[field_name] = field
        if opts.model_dump_only_pk and opts.model:
            # If primary key is automatically generated (nominal case), we
            # must make sure this field is read-only
            if opts.model._auto_id_field is True:
                field_name = opts.model._meta['id_field']
                id_field = declared_fields.get(field_name)
                if id_field:
                    # Copy to prevent alteration of a possible parent class's field
                    id_field = copy.copy(id_field)
                    id_field.dump_only = True
                    declared_fields[field_name] = id_field
        return declared_fields
717149
public static String getString(Object from, Field field)
    {
        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(field);
        Object object = getObject(from, field);
        return object != null ? accessor.toString(object) : null;
    }
524464
@SuppressWarnings("unchecked")
    private static String converter(String fieldName, Object object) {
        StringBuilder builder = new StringBuilder();
        if (Checker.isNotEmpty(fieldName)) {
            builder.append("\"").append(fieldName).append("\":");
        }
        if (object instanceof Collection) {
            List list = (List) object;
            builder.append("[");
            list.forEach(obj -> builder.append(converter(ValueConsts.EMPTY_STRING, obj)));
            return builder.substring(0, builder.length() - 1) + "],";
        } else if (object instanceof Map) {
            Map map = (Map) object;
            builder.append("{");
            map.forEach((k, v) -> builder.append(converter(k.toString(), v)));
            return builder.substring(0, builder.length() - 1) + "},";
        } else if (Checker.isEmpty(fieldName)) {
            builder.append("\"").append(object).append("\",");
        } else {
            builder.append("\"").append(object).append("\",");
        }
        return builder.toString();
    }
1351905
public String getHeaderField(String fieldName) {
        // headers map is null for all regular response calls except when made as a batch request
        if (this.headers == null) {
            if (this.connection != null) {
                return this.connection.getHeaderField(fieldName);
            } else {
                return null;
            }
        } else {
            return this.headers.get(fieldName);
        }
    }
654738
public V getValue(T object) {
        try {
            if (this.getMethod != null) {
                return (V)this.getMethod.invoke(object);
            } else {
                return (V)this.field.get(object);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
1149374
public void declareRequestedFieldname(String name) {
        if (name.endsWith(".*")) {
            stringSetValues.put(name, new HashMap<>());
            stringSetPrefixes.put(name.substring(0, name.length() - 1), name);
        }
    }
1160511
public static ObjectNode getObjAndRemove(ObjectNode obj, String fieldName) {
		ObjectNode result = null;
		if (obj != null) {
			result = obj(remove(obj, fieldName));
		}
		return result;
	}
1198608
public Reflect get(@NonNull String fieldName) throws ReflectionException {
      Field f = getField(fieldName);

      if (f == null) {
         throw new ReflectionException(new NoSuchFieldException(fieldName + " is not a valid field for " + clazz));
      }

      boolean isAccessible = f.isAccessible();
      try {
         if (accessAll) {
            f.setAccessible(true);
         }
         return onObject(f.get(object));
      } catch (IllegalAccessException e) {
         e.printStackTrace();
         throw new ReflectionException(e);
      } finally {
         f.setAccessible(isAccessible);
      }

   }
1244516
public static void setFieldValue(Object object, String fieldName, Object value) throws NoSuchFieldException {
        Field field = getDeclaredField(object, fieldName);
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        try {
            field.set(object, value);
        } catch (IllegalAccessException e) {
            logger.error("不可能抛出的异常:{}", e.getMessage());
        }
    }
382213
public static Field getField(final Class<?> clazz, final String fieldName) {
        //Define return type
        //
        Field
            field = null;

        //For each class in the hierarchy starting with the current class, try to find the declared field
        //
        for (Class<?> current = clazz; current != null && field == null; current = current.getSuperclass()) {
            try {
                //Attempt to get the field, if exception is thrown continue to the next class
                //
                field =
                    current
                        .getDeclaredField(
                            fieldName
                        );
            }
            catch (final NoSuchFieldException e) {
                //ignore and continue searching
                //
            }
        }

        //Return the field we found
        //
        return
            field;
    }
523002
public static Field getDeclaredField(Class<?> clz, final String fieldName) {
    for (Class<?> s = clz; s != Object.class; s = s.getSuperclass()) {
      try {
        return s.getDeclaredField(fieldName);
      } catch (NoSuchFieldException ignored) {
      }
    }
    return null;
  }
365040
public static Field getField(final Class cls, final String fieldName) {
		return getField(cls, fieldName, false);
	}
686402
public static boolean setField(Object object, String fieldName, Object value) {
		char c = fieldName.charAt(0);

		if (c >= 'a' && c <= 'z') {
			c -= 'a' - 'A';
			fieldName = c + fieldName.substring(1);
		}

		String methodName = "set" + fieldName;
		Class<?>[] returnType = new Class<?>[1];
		Class<?> objectClass = object.getClass();

		Method getMethod = getMethod(objectClass, "get" + fieldName);

		if (getMethod == null) {
			getMethod = getMethod(objectClass, "is" + fieldName);
		}

		if (getMethod == null) {
			return false;
		}

		returnType[0] = getMethod.getReturnType();

		return silentInvoke(object, methodName, returnType, value);
	}