我的控制器类是这样的:
@RestController
@RequestMapping("/api/admin")
@SecurityRequirement(name = "E-Commerce Application")
public class AddressController {
@Autowired
private AddressService addressService;
@GetMapping("/addresses")
public ResponseEntity<List<AddressDTO>> getAddresses() {
List<AddressDTO> addressDTOs = addressService.getAddresses();
return new ResponseEntity<List<AddressDTO>>(addressDTOs, HttpStatus.FOUND);
}
}
我正在尝试获取“getAddresses”方法注释“GetMapping”值“/addresses”。我在调试时发现了annotation.h.memberFields变量中的值。
我尝试过,像这样,它在输出中弹出,但如何在我的程序中获取“值”字段成为挑战。
public class ClassMethodsTool {
public static void main(String[] args) {
Class<?> myClass = AddressController.class;
Method[] methods = myClass.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
Annotation[] annotations = method.getAnnotations();
for (Annotation a: annotations
) {
System.out.println(method.getDeclaredAnnotations()[0]);
}
}
}
}
这个弹跳
@org.springframework.web.bind.annotation.GetMapping(path={}, headers={}, name="", produces={}, params={}, value={"/addresses/{addressId}"}, consumes={})
value={"/addresses/{addressId}"} 我想在程序中获取这个值。
我尝试了很多方法,还是没有成功。需要帮助。
忽略任何异常:
Method method = AddressController.class.getDeclaredMethod("getAddresses");
GetMapping annotation = method.getAnnotation(GetMapping.class);
String[] paths = annotation.value();
在现有代码中,您还可以将注释转换为
GetMapping
。如果您想查看 Annotation
类型的任何变量的注释类型是什么,您可以使用 annotationType()
。不要使用 getClass()
,这将返回一些 JDK 内部类。
调整您的代码以完全安全的方式获取路径:
public class ClassMethodsTool {
public static void main(String[] args) {
Class<?> myClass = AddressController.class;
Method[] methods = myClass.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
Annotation[] annotations = method.getAnnotations();
for (Annotation a: annotations) {
System.out.println(a);
if (a.annotationType() == GetMapping.class) {
GetMapping getMapping = (GetMapping) a;
String[] paths = getMapping.value();
}
}
}
}
}