如何通过Java代码获取方法上GetMapping注解的value字段值
解决反射提取@GetMapping注解value值的问题
你需要将通用的Annotation对象转换为具体的GetMapping注解类型,才能调用其方法获取value字段的值。修改后的工具类代码如下:
import org.springframework.web.bind.annotation.GetMapping; import java.lang.reflect.Method; public class ClassMethodsTool { public static void main(String[] args) { Class<?> myClass = AddressController.class; Method[] methods = myClass.getDeclaredMethods(); for (Method method : methods) { // 判断方法是否标注了@GetMapping注解 if (method.isAnnotationPresent(GetMapping.class)) { // 获取具体的GetMapping注解实例 GetMapping getMapping = method.getAnnotation(GetMapping.class); // 获取value字段值(value和path是别名,效果一致) String[] paths = getMapping.value(); // 遍历输出路径 for (String path : paths) { System.out.printf("方法%s的@GetMapping路径:%s%n", method.getName(), path); } } } } }
关键说明:
- 通用
Annotation接口没有定义value()方法,必须转换为对应的注解实现类(这里是GetMapping)才能访问其字段 GetMapping的value()和path()方法是互为别名的,调用任意一个都能获取路径数组- 因为注解允许配置多个路径(比如
@GetMapping({"/addresses", "/list"})),所以返回值是字符串数组,需要遍历处理
内容的提问来源于stack exchange,提问作者Sun
相关产品推荐
相关产品推荐

