编译器会优化掉未使用的私有方法吗?

Will compilers optimize out unused private methods?

如果私有方法是内联的,javac 会忽略它们吗? 例如

public class Test {
  public static void main(String[] args){
    System.out.println(sayHello());
  }
  private static String sayHello(){
    return "Hello World";
  }
}

但是如果这个方法然后被反射访问呢?

 System.out.println(Test.class.getMethod("sayHello").invoke(null));

编译器如何知道是否内联方法并删除它?

我听从了用户 Jesper 的建议并在此代码上使用了 javap:

package Whosebug;

public class CompilerOptimize {
    public static void main(String[] args){
        System.out.println(sayHello());
    }

    private static String sayHello(){
        return "Hello World";
    }

    private static void bananas() {
        System.out.println("Monkey!");
    }
}

使用方法sayHello,未使用bananas

带-p参数的运行javap在class和Java8编译后的结果是:

public class whosebug.compilerOptimize {
  public whosebug.compilerOptimize();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: invokestatic  #3                  // Method sayHello:()Ljava/lang/String;
       6: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       9: return

  private static java.lang.String sayHello();
    Code:
       0: ldc           #5                  // String Hello World
       2: areturn

  private static void bananas();
    Code:
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #6                  // String Monkey!
       5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return
}

字节码注释中提到了方法bananassayHello也有)。

Will compilers optimize out unused private methods?

不是真的。