背景:
很長一段時間里,Java程序員一直在發明不同的方式使得方法參數的名字能保留在Java字節碼中,並且能夠在運行時獲取它們(比如,Paranamer類庫)。最終,在Java 8中把這個強烈要求的功能添加到語言層面(通過反射API與Parameter.getName()方法)與字節碼文件(通過新版的javac的–parameters選項)中。
public static void speak(String word){ System.out.println(word); } public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method = ParameterNameTest.class.getMethod("speak",String.class); method.invoke(null,"你好"); Parameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { Parameter p = parameters[i]; System.out.println(p.getName()); } }
如果不使用–parameters參數來編譯這個類,然后運行這個類,會得到下面的輸出:
你好
arg0
如果使用–parameters參數來編譯這個類,程序的結構會有所不同(參數的真實名字將會顯示出來):
你好
word
Maven的設置方式:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <compilerArgument>-parameters</compilerArgument> <source>1.8</source> <target>1.8</target> </configuration> </plugin>
IDEA的設置方式:
Setting > Build,Execution,Depoyment > Compiler > Java Compiler ,在"Additional command line parameters"中加上"-parameters"參數