反射獲取方法的參數名(非類型)

方法一:如果項目依賴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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容