spring - Spring 如何在没有调试信息的情况下获取参数名称

标签 spring spring-mvc reflection

@RequestMapping("/form")
public String form(Model model, Integer id)

例如,spring可以知道参数id的名称是id,并在运行时将请求参数的值绑定(bind)到它

最佳答案

这是 JDK 8 中引入的 javac 功能。您需要包含 -parameters javac 命令行选项来激活它。然后您将能够获取如下参数名称:

String name = String.class.getMethod("substring", int.class).getParameters()[0].getName()
System.out.println(name);

来自 Spring 文档 3.3 Java 8 (as well as 6 and 7)

You can also use Java 8’s parameter name discovery (based on the -parameters compiler flag) as an alternative to compiling your code with debug information enabled.

如 javadoc 中指定的 ParameterNameDiscoverer类:

Parameter name discovery is not always possible, but various strategies are available to try, such as looking for debug information that may have been emitted at compile time, and looking for argname annotation values optionally accompanying AspectJ annotated methods.

这是 Spring 项目中相关 JIRA 项目的链接 Java 8 parameter name discovery for methods and constructors

JDK增强提案JEP 118: Access to Parameter Names at Runtime

关于spring - Spring 如何在没有调试信息的情况下获取参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36466913/

相关文章:

java - 禁用webclient ssl验证springboot 2.0.4

java - Common Lisp 中的类自省(introspection)

java - 重构代码的好方法

http - 从 HTTP 过滤器访问 URL 处理程序模式

java - 单选按钮标签更改

java - 如何使用java反射加载最终类

java - Java 中的 SecurityManager 有没有办法选择性地授予 ReflectPermission ("suppressAccessChecks")?

java - 使用 pointcut=@annotation 进行 @AfterThrowing 的方面运行了两次

javascript - 在 javascript POST 中发送 CSRF token 会出现错误

java - 如何对 Spring ResourceHandlerRegistry 服务的静态资源进行单元测试