What is the difference between getFields and getDeclaredFields in Java reflection

前端 未结 4 664
广开言路
广开言路 2020-11-29 17:22

I\'m a little confused about the difference between the getFields method and the getDeclaredFields method when using Java reflection.

I re

4条回答
  •  温柔的废话
    2020-11-29 17:46

    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);
    }
    

提交回复
热议问题