【问题标题】:How to keep argument names of interface after compilation in Java?Java编译后如何保留接口的参数名称?
【发布时间】:2018-09-19 07:58:43
【问题描述】:

我想在Java编译后保留接口方法的参数名称。

下面是一个例子。

编译前:

interface IFoo {
    void hello(String what);
}

使用javac -g:vars IFoo.java编译后

interface IFoo {
    void hello(String str);
}

参数what 重命名为str

如何保留参数名称?

【问题讨论】:

    标签: java interface javac


    【解决方案1】:

    编译时需要生成调试信息。 这就是 Javac 选项 -g 所做的:

    -g — 生成所有调试信息,包括局部变量。


    如果你使用的是 Maven,你可以在compiler plugin's configuration 中设置<debug>true</debug>

    【讨论】:

    • 虽然对类方法和静态接口方法很有魅力,但它不适用于非静态接口方法。
    【解决方案2】:

    参数或局部变量没有名称,只有一个数字。

    我相信添加局部变量名称的命令行参数是-parameters,以启用通过反射访问https://www.beyondjava.net/reading-java-8-method-parameter-named-reflection

    确定/猜测变量名是反编译器的工作。我使用的 Fernflower 做得很合理。

    输入

    import java.util.stream.Stream;
    
    interface IFoo {
        public abstract void hello(String what);
    
        public static void print(String... args) {
            Stream<String> stream = Stream.of(args);
            stream.forEach(System.out::println);
        }
    }
    

    使用 Fernflower 输出

    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by Fernflower decompiler)
    //
    import java.io.PrintStream;
    import java.util.function.Consumer;
    import java.util.stream.Stream;
    
    interface IFoo {
        void hello(String what);
    
        static void print(String... args) {
            Stream<String> stream = Stream.of(args);
            PrintStream var10001 = System.out;
            System.out.getClass();
            stream.forEach(var10001::println);
        }
    }
    

    注意:System.out.getClass();javac 编译器生成,用于测试 null 值。

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2018-02-16
      • 2019-03-12
      • 1970-01-01
      相关资源
      最近更新 更多