클래스에 선언된 모든 필드 가져오기

엔터티 클래스의 필드 가져오기

1. entity.getClass().getDeclaredFields()이 메서드는 전용 필드와 보호 필드를 포함하여 클래스에 선언된 모든 필드를 반환하지만 상위 클래스에서 상속된 필드는 포함하지 않습니다.

2. entity.getClass().getFields()메서드, 이 메서드는 이 클래스와 해당 상위 클래스에 있는 모든 공개 필드의 배열을 반환합니다.

3. 프라이빗 필드와 보호 필드를 포함하여 상위 클래스에서 상속된 모든 필드를 가져옵니다. getDeclaredFields()리플렉션 API의 메서드를 사용하여 상위 클래스의 필드를 반복적으로 가져올 수 있습니다.

4.데모

다음은 리플렉션 API를 사용하여 상속된 필드를 포함한 모든 필드를 가져올 수 있는 샘플 코드입니다.

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

출력은 다음과 같습니다

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

추천

출처blog.csdn.net/zhoqua697/article/details/130808076