Get all fields declared in a class

Get the fields in the entity class

1. entity.getClass().getDeclaredFields()The method returns all fields declared in the class, including private fields and protected fields, but does not include fields inherited from the parent class.

2. entity.getClass().getFields()Method, this method returns an array of all public fields in this class and its parent class.

3. Obtain all fields inherited from the parent class, including private fields and protected fields. You can use getDeclaredFields()the method in the reflection API to recursively obtain the fields of the parent class.

4.demo

Here is a sample code that can use the reflection API to get all fields including inherited fields:

import java.lang.reflect.Field;

public class Example {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个子类对象
        Child child = new Child();

        // 获取子类中声明的所有字段,包括私有字段和受保护字段
        Field[] declaredFields = child.getClass().getDeclaredFields();
        System.out.println("子类中声明的字段:");
        for (Field field : declaredFields) {
    
    
            System.out.println(field.getName());
        }

        // 获取子类及其父类中所有公共字段
        Field[] publicFields = child.getClass().getFields();
        System.out.println("子类及其父类中的公共字段:");
        for (Field field : publicFields) {
    
    
            System.out.println(field.getName());
        }

        // 获取子类及其父类中所有字段,包括私有字段和受保护字段
        Field[] allFields = getAllFields(child.getClass());
        System.out.println("子类及其父类中的所有字段:");
        for (Field field : allFields) {
    
    
            System.out.println(field.getName());
        }
    }

    // 递归获取子类及其父类中所有字段
    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;
    }
}

// 父类
class Parent {
    
    
    public int publicField;
    protected String protectedField;
    private boolean privateField;
}

// 子类
class Child extends Parent {
    
    
    public double publicDoubleField;
    protected Object protectedObjectField;
    private byte[] privateByteArrayField;
}

The output is:

子类中声明的字段:
publicDoubleField
protectedObjectField
privateByteArrayField
子类及其父类中的公共字段:
publicField
子类及其父类中的所有字段:
publicDoubleField
protectedObjectField
privateByteArrayField
publicField
protectedField
privateField

Guess you like

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