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   zhangyukun  阅读(2214)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 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 线程池

导航

< 2025年3月 >
23 24 25 26 27 28 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 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示