IDEA 支持JDK1.8的-parameters

背景:

很长一段时间里,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"参数

猜你喜欢

转载自www.cnblogs.com/aligege/p/12448597.html