package com.huashe.park.common.animations.mybatis;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FieldMetadataCache {
    private static final Map<Class<?>, List<Field>> cache = new ConcurrentHashMap<>();

    public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotation) {

        return cache.computeIfAbsent(clazz, key -> {
            List<Field> fields = new ArrayList<>();
            Class<?> currentClass = clazz;
            // 递归向上遍历所有父类
            while (currentClass != null && currentClass != Object.class) {
                Arrays.stream(currentClass.getDeclaredFields()).filter(f -> f.isAnnotationPresent(annotation))
                    .forEach(filed -> {
                        if (!filed.isAccessible()) {
                            filed.setAccessible(true);
                        }
                        fields.add(filed);
                    });
                currentClass = currentClass.getSuperclass();
            }
            return Collections.unmodifiableList(fields);
        });
    }
}
