Method.getParameterAnnotations
返回值解释
Method.getParameterAnnotations()各个维度理解:
返回值:annotations
返回值类型:Annotation[][]
返回值:annotations:
位置:annotations[i][j],第i个参数,第j个注解,整体表示一个注解类型
图示:
代码演示
ZQRequestParam
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ZQRequestParam {
String value() default "";
}
ZQValid
@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface ZQValid {
String value() default "";
}
DemoServiceImpl
public class DemoServiceImpl {
public void testGetParameterAnnotations(@ZQRequestParam("name") @ZQValid("name1") String name,
@ZQRequestParam("age") int age,
@ZQRequestParam("telphone") String telphone){
}
}
Test
public class Test {
public static void main(String[] args) throws NoSuchMethodException {
Class<DemoServiceImpl> clazz = DemoServiceImpl.class;
Method method = clazz.getMethod("testGetParameterAnnotations", String.class, int.class, String.class);
Annotation[][] annotations = method.getParameterAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println("我是第" + (i + 1) + "个参数,共有" + annotations[i].length + "个注解");
for (int j = 0; j < annotations[i].length; j++) {
if (annotations[i][j] instanceof ZQRequestParam) {
System.out.println("第" + (i + 1) + "参数,第" + (j + 1) + "个注解,ZQRequestParam.value=" + ((ZQRequestParam) annotations[i][j]).value());
} else if (annotations[i][j] instanceof ZQValid) {
System.out.println("第" + (i + 1) + "参数,第" + (j + 1) + "个注解,ZQValid.value=" + ((ZQValid) annotations[i][j]).value());
}
}
}
}
}
输出结果
使用场景
用于访问MVC前端通过HTTPS访问后端,获得形参参数位置-参数注解位置的注解,并整理出访问方法的形参位置与形参名称name(如@RequestParam(value=“name”))做映射关系。