Get the current class and all fields inherited from the parent class, including private fields and protected fields

1. demo

    /**
     * <p>获取自己及继承自父类的所有字段,包括私有字段和受保护字段,可以使用反射 API 中的 getDeclaredFields() 方法来递归获取父类的字段。</p>
     *
     * @param clazz clazz
     * @return {@link Field[] }
     * @see Class<?>
     * @see Field[]
     */
    private static Field[] getAllFields(Class<?> clazz) {
    
    
        Field[] fields = clazz.getDeclaredFields();
        Class<?> parent = clazz.getSuperclass();
        if (parent != null) {
    
    
            Field[] parentFields = getAllFields(parent);
            Field[] allFields = new Field[fields.length + parentFields.length];
            System.arraycopy(fields, 0, allFields, 0, fields.length);
            System.arraycopy(parentFields, 0, allFields, fields.length, parentFields.length);
            fields = allFields;
        }
        return fields;
    }

2. Thoughts triggered

fields = allFieldsDoes the assignment need to consider the insufficient length of fields.

The answer is: No need

1.Cause analysis

In Java, an array is a reference type, and the array variable stores the address of the array object in memory, not the value of the array itself. Therefore, when doing an array assignment, you are actually assigning a reference to an array object to another array variable, rather than copying the value of the array into another array.

For example, suppose there are two array variables aand b, both of which refer to the same array object:

int[] a = {
    
    1, 2, 3};
int[] b = a;

Here, the variables aand bboth refer to {1, 2, 3}the address of the array in memory. Therefore, when executing b = a;, the reference of the array object is actually copied to b, that is, bit apoints to the same array object as . This type of assignment is called reference assignment.

If you need to copy the value of one array to another array, you can use System.arraycopy()the method or the copy method of the array clone(). For example:

int[] a = {
    
    1, 2, 3};
int[] b = newint[3];
System.arraycopy(a, 0, b, 0, 3); // 将数组 a 的值复制到数组 b 中

or:

int[] a = {1, 2, 3};
int[] b = a.clone(); // 使用数组的 clone() 方法复制数组 a 的值到数组 b 中

It should be noted that when using System.arraycopy()the method or clone()method to copy an array, the value of the array object is copied, not the array object itself. Therefore, if the elements in the array are reference types, then the references to the elements are copied, not the elements themselves. If you need to copy an element of reference type, you need to use deep copy to copy the element itself.

Guess you like

Origin blog.csdn.net/zhoqua697/article/details/130843770