反射获取方法的参数名(非类型)

方法一:如果项目依赖spring,可以使用

String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(methods);

上面的methods是通过反射获得的Method对象

方法二:jdk1.8提供了获取参数名的方法

但是在编译的时候要加上–parameters参数,如果不加这个参数会得到参数名为arg0...

Parameter[] parameters = methods.getParameters();
System.out.println(parameters[0].getName());

但是如果使用maven,只需要在编译插件上加上一个配置<compilerArgument>-parameters</compilerArgument>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <compilerArgument>-parameters</compilerArgument>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
</plugin>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。