注解工具类支持Lambda获取某注解属性值

This commit is contained in:
LinRuChang 2022-09-30 11:36:30 +08:00
parent e59548ebbf
commit 80f973093c
3 changed files with 32 additions and 1 deletions

View File

@ -7,6 +7,8 @@ import cn.hutool.core.annotation.scanner.TypeAnnotationScanner;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
@ -229,6 +231,26 @@ public class AnnotationUtil {
return ReflectUtil.invoke(annotation, method);
}
/**
* 获取指定注解属性的值<br>
* 如果无指定的属性方法返回null
*
* @param <A> 注解类型
* @param <R> 注解类型值
* @param annotationEle {@link AnnotatedElement}可以是ClassMethodFieldConstructorReflectPermission
* @param annotationType 注解类型
* @param propertyName 属性名例如注解中定义了name()方法 此处传入name
* @return 注解对象
* @throws UtilException 调用注解中的方法时执行异常
*/
public static <A extends Annotation, R> R getAnnotationValue(AnnotatedElement annotationEle, Class<A> annotationType, Func1<A, R> propertyName) {
if(propertyName == null) {
return null;
}else {
return getAnnotationValue(annotationEle,annotationType, LambdaUtil.getMethodName(propertyName));
}
}
/**
* 获取指定注解中所有属性值<br>
* 如果无指定的属性方法返回null

View File

@ -26,4 +26,6 @@ public @interface AnnotationForTest {
@Alias("value")
String retry() default "";
String[] names() default "";
}

View File

@ -1,5 +1,6 @@
package cn.hutool.core.annotation;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert;
import org.junit.Test;
@ -34,6 +35,12 @@ public class AnnotationUtilTest {
}
@Test
public void getAnnotationValueTest2() {
String[] names = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest.class, AnnotationForTest::names);
Assert.assertTrue(ArrayUtil.equals(names, new String[]{"测试1", "测试2"}));
}
@Test
public void getAnnotationSyncAlias() {
// 直接获取
@ -45,7 +52,7 @@ public class AnnotationUtilTest {
Assert.assertTrue(AnnotationUtil.isSynthesizedAnnotation(annotation));
}
@AnnotationForTest("测试")
@AnnotationForTest(value = "测试", names = {"测试1", "测试2"})
@RepeatAnnotationForTest
static class ClassWithAnnotation{
public void test(){