先來看一段 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] 表示第三個參數有兩個註解。
😆,你就說神不神奇。