java 获取方法参数名字
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
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]
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());
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
该功能需要在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>
能耍的时候就一定要耍,不能耍的时候一定要学。
--天道酬勤,贵在坚持posted on 2022-07-09 15:31 zhangyukun 阅读(2299) 评论(0) 收藏 举报
浙公网安备 33010602011771号