zoukankan      html  css  js  c++  java
  • 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"参数

  • 相关阅读:
    思考问题的方式
    领域模型驱动设计读书笔记
    Oracle树形表和递归查询
    java中List , Set , Array相互转换
    JAVA两个数组间元素的比较(找出相同或者不同元素)
    java中的过滤器写法
    打印功能--调整表头
    @WebFilter注解
    深入理解JVM-内存模型(jmm)和GC
    vue生命周期函数
  • 原文地址:https://www.cnblogs.com/aligege/p/12448597.html
Copyright © 2011-2022 走看看