java 获取方法参数名字
1 自定义注解获取
在方法参数前面加一个注解标注这个参数的名字(Mybatis dao 层标注参数名字就这样做的 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //自定义@param注解 @Target (ElementType.PARAMETER) @Retention (RetentionPolicy.RUNTIME) @Documented public @interface Param { String value(); } //声明参数名 public void foo( @Param ( "name" ) String name, @Param ( "count" ) int count){ System.out.println( "name:=" + name + ",count=" + count); } //获取 Method foo = ParameterDemo. class .getMethod( "foo" , String. class , int . class ); Annotation[][] parameterAnnotations = foo.getParameterAnnotations(); for (Annotation[] parameterAnnotation : parameterAnnotations) { for (Annotation annotation : parameterAnnotation) { if (annotation instanceof Param){ System.out.println(((Param) annotation).value()); } } } //获取结果 name count |
2 spring 提供了获取 方法参数名字的方法
spring借助了 asm 工具包(asm-tool)
1 2 3 4 5 6 7 8 9 10 11 | //使用Spring的LocalVariableTableParameterNameDiscoverer获取 public void foo(String name, int count){ System.out.println( "name:=" + name + ",count=" + count); } Method foo = ParameterDemo. class .getMethod( "foo" , String. class , int . class ); String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(foo); System.out.println(Arrays.toString(parameterNames)); //获取结果 [name, count] |
asm-tool获取参数名字:
1 2 3 4 5 6 7 8 | public String common(String name) { return name; } Method method = ClassUtil.getMethod(AsmMethodsTest. class , "common" , String. class ); List<String> param = AsmMethods.getParamNamesByAsm(method); Assert.assertEquals( "[name]" , param.toString()); |
3 java8 提供了获取参数名字的实现(前提是在编译过程中要使用-paramters参数)
1 2 3 4 5 6 7 8 9 10 11 12 | public void foo(String name, int count){ System.out.println( "name:=" + name + ",count=" + count); } //通过反射获取 Method foo = ParameterDemo. class .getMethod( "foo" , String. class , int . class ); Parameter[] parameters = foo.getParameters(); for (Parameter parameter : parameters) { System.out.println(parameter.getName()); } //获取结果 name count |
该功能需要在javac
编译时开启-parameters
参数,而为了兼容性该参数默认是不开启的,如果使用Maven构建的话可以如此配置:
1 2 3 4 5 6 7 8 9 10 11 | <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source> 8 </source> <target> 8 </target> <compilerArgs> <compilerArg>-parameters</compilerArg> </compilerArgs> </configuration> </plugin> |
能耍的时候就一定要耍,不能耍的时候一定要学。
--天道酬勤,贵在坚持posted on 2022-07-09 15:31 zhangyukun 阅读(2214) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
2019-07-09 mysql innodb 的 逻辑存储结构
2018-07-09 Queque 方法对比和分类
2018-07-09 阻塞队列 BlockingQueue
2018-07-09 Java 线程池