diff --git a/hutool-core/src/main/java/cn/hutool/core/annotation/CacheableSynthesizedAnnotationAttributeProcessor.java b/hutool-core/src/main/java/cn/hutool/core/annotation/CacheableSynthesizedAnnotationAttributeProcessor.java new file mode 100644 index 000000000..3329bc2f1 --- /dev/null +++ b/hutool-core/src/main/java/cn/hutool/core/annotation/CacheableSynthesizedAnnotationAttributeProcessor.java @@ -0,0 +1,49 @@ +package cn.hutool.core.annotation; + +import cn.hutool.core.map.multi.RowKeyTable; +import cn.hutool.core.map.multi.Table; +import cn.hutool.core.util.ObjectUtil; + +import java.util.Collection; +import java.util.Comparator; + +/** + * 带缓存功能的{@link SynthesizedAnnotationAttributeProcessor}实现, + * 构建时需要传入比较器,获取属性值时将根据比较器对合成注解进行排序, + * 然后选择具有所需属性的,排序最靠前的注解用于获取属性值 + * + * @param 合成注解类型 + * @author huangchengxing + */ +public class CacheableSynthesizedAnnotationAttributeProcessor> implements + SynthesizedAnnotationAttributeProcessor { + + private final Table, Object> valueCaches = new RowKeyTable<>(); + private final Comparator annotationComparator; + + /** + * 创建一个带缓存的注解值选择器 + * + * @param annotationComparator 注解比较器,排序更靠前的注解将被优先用于获取值 + */ + public CacheableSynthesizedAnnotationAttributeProcessor(Comparator annotationComparator) { + this.annotationComparator = annotationComparator; + } + + @SuppressWarnings("unchecked") + @Override + public T getAttributeValue(String attributeName, Class attributeType, Collection synthesizedAnnotations) { + Object value = valueCaches.get(attributeName, attributeType); + // 此处理论上不可能出现缓存值为nul的情况 + if (ObjectUtil.isNotNull(value)) { + return (T)value; + } + value = synthesizedAnnotations.stream() + .filter(ma -> ma.hasAttribute(attributeName, attributeType)) + .min(annotationComparator) + .map(ma -> ma.getAttribute(attributeName)) + .orElse(null); + valueCaches.put(attributeName, attributeType, value); + return (T)value; + } +} diff --git a/hutool-core/src/main/java/cn/hutool/core/annotation/SynthesizedAnnotationAttributeProcessor.java b/hutool-core/src/main/java/cn/hutool/core/annotation/SynthesizedAnnotationAttributeProcessor.java new file mode 100644 index 000000000..022afb8ce --- /dev/null +++ b/hutool-core/src/main/java/cn/hutool/core/annotation/SynthesizedAnnotationAttributeProcessor.java @@ -0,0 +1,24 @@ +package cn.hutool.core.annotation; + +import java.util.Collection; + +/** + * 合成注解属性选择器。用于中合成注解中从指定类型的注解里获取到对应的属性值 + * + * @author huangchengxing + */ +@FunctionalInterface +public interface SynthesizedAnnotationAttributeProcessor> { + + /** + * 从一批被合成注解中,获取指定名称与类型的属性值 + * + * @param attributeName 属性名称 + * @param attributeType 属性类型 + * @param synthesizedAnnotations 被合成的注解 + * @param 属性类型 + * @return 属性值 + */ + T getAttributeValue(String attributeName, Class attributeType, Collection synthesizedAnnotations); + +}