获取别名支持后的注解

This commit is contained in:
VampireAchao 2022-03-01 22:59:28 +08:00
parent 9c3cf705c6
commit 0e5329850a
3 changed files with 39 additions and 9 deletions

View File

@ -2,15 +2,11 @@ package cn.hutool.core.annotation;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@ -215,4 +211,26 @@ public class AnnotationUtil {
final Map memberValues = (Map) ReflectUtil.getFieldValue(Proxy.getInvocationHandler(annotation), "memberValues");
memberValues.put(annotationField, value);
}
/**
* 获取别名支持后的注解
*
* @param annotationEle 被注解的类
* @param annotationType 注解类型Class
* @param <T> 注解类型
* @return 别名支持后的注解
*/
@SuppressWarnings("unchecked")
public static <T extends Annotation> T getAnnotationAlias(AnnotatedElement annotationEle, Class<T> annotationType) {
T annotation = getAnnotation(annotationEle, annotationType);
Object o = Proxy.newProxyInstance(annotationType.getClassLoader(), new Class[]{annotationType}, (proxy, method, args) -> {
Alias alias = method.getAnnotation(Alias.class);
if (ObjectUtil.isNotNull(alias) && StrUtil.isNotBlank(alias.value())) {
Method aliasMethod = annotationType.getMethod(alias.value());
return ReflectUtil.invoke(annotation, aliasMethod);
}
return method.invoke(args);
});
return (T) o;
}
}

View File

@ -10,7 +10,6 @@ import java.lang.annotation.Target;
* 注解类相关说明见https://www.cnblogs.com/xdp-gacl/p/3622275.html
*
* @author looly
*
*/
// Retention注解决定MyAnnotation注解的生命周期
@Retention(RetentionPolicy.RUNTIME)
@ -23,5 +22,8 @@ public @interface AnnotationForTest {
*
* @return 属性值
*/
String value();
String value() default "";
@Alias("value")
String retry() default "";
}

View File

@ -12,6 +12,16 @@ public class AnnotationUtilTest {
}
@Test
public void getAnnotationSyncAlias() {
// 直接获取
Assert.assertEquals("", ClassWithAnnotation.class.getAnnotation(AnnotationForTest.class).retry());
// 加别名适配
AnnotationForTest annotation = AnnotationUtil.getAnnotationAlias(ClassWithAnnotation.class, AnnotationForTest.class);
Assert.assertEquals("测试", annotation.retry());
}
@AnnotationForTest("测试")
static class ClassWithAnnotation{
public void test(){