先来看一段 Spring MVC 经常用到的定义在方法参数上的注解:
@RestController
@RequestMapping("/param")
public class ParamTestController {
@PostMapping("/upload")
public void upload(@RequestParam("userId") long userId, @RequestParam(value = "file", required = false) MultipartFile file) {
System.out.println(Objects.isNull(file));
}
}
比如我们常用的注解 @RequestParams
,是定义在方法参数上的,那是怎么通过 Java 获取方法参数上的注解信息呢?参数前可以添加多个注解,一个参数上不能添加多个相同的注解,相同的注解可以添加到不同的参数上。
下面有这样一个类,现在需要获取到参数上的注解信息。
public class SkyService {
public String blue(int color,
@CustomAnnotation(value = "one")
@CustomAnnotation1(value = "two")
@CustomAnnotation2(value = "three") String big,
@CustomAnnotation1("four") @CustomAnnotation2("five") String bala) {
return "What blue sky it is";
}
}
来看代码:
@Test
public void testParamAnnotation() {
// 获取方法的反射对象
Method[] methods = SkyService.class.getMethods();
Class<?>[] parameterTypes = methods[0].getParameterTypes();
Annotation[][] pa = methods[0].getParameterAnnotations();
// 二维数组遍历,第一维是参数的个数,第二维是具体的注解值
for (int i = 0; i < parameterTypes.length; i++) {
// 每个参数对应的注解数组
for (Annotation annotation : pa[i]) {
if (annotation instanceof CustomAnnotation) {
System.out.println(((CustomAnnotation) annotation).value());
} else if (annotation instanceof CustomAnnotation1) {
System.out.println(((CustomAnnotation1) annotation).value());
} else if (annotation instanceof CustomAnnotation2) {
System.out.println(((CustomAnnotation2) annotation).value());
}
}
}
}
从上图的断点中可以看出,Annotation[][] pa = methods[0].getParameterAnnotations();
得到的是一个二维数组,第一维是参数的个数,第二维是注解数组,也就是说第一个参数的下标为 0,第二个参数的下标为 1,以此类推。如果某个参数没有注解标注得到的就是一个长度为 0 的数组,比如 SkyService.blue
方法中的有三个参数,第一个 color 参数是没有注解标注的,可以看到 pa[0] 对应的数组长度是 0。然后 pa[1] 表示第二个参数有三个注解,pa[2] 表示第三个参数有两个注解。
😆,你就说神不神奇。