1 自定义注解获取

 

  在方法参数前面加一个注解标注这个参数的名字(Mybatis dao 层标注参数名字就这样做的 )

//自定义@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
  • 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.

  

2 spring 提供了获取 方法参数名字的方法

  

  spring借助了 asm 工具包(asm-tool)

//使用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]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

  

asm-tool获取参数名字:

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());
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

  

 

 

3 java8 提供了获取参数名字的实现(前提是在编译过程中要使用-paramters参数)

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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

  

该功能需要在javac编译时开启-parameters参数,而为了兼容性该参数默认是不开启的,如果使用Maven构建的话可以如此配置:

<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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.