最终的静态变量操作,编译还是运行时?

dim*_*s93 4 java

最终的静态变量操作是在运行时还是编译时发生的?例如:

public static final int ID_1 = 1;
public static final int ID_2 = 2;

public static int test(){
    return ID_1 + ID_2; // Does this addition execute in compile or runtime ?
}
Run Code Online (Sandbox Code Playgroud)

eug*_*ioy 6

这里有一个提示:https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

它说:

如果将基本类型或字符串定义为常量并且在编译时已知该值,则编译器会将代码中的常量名称替换为其值.

因此,一旦完成并最终完成了1 + 2该方法,那么优化也是合乎逻辑的,并且只需3在编译时使用.

为了在实践中证明它,您可以编译代码然后反编译它以查看正在发生的事情.

我尝试使用JD-GUI,这是我在反编译代码时得到的:

    public class TestCompileOrRuntime
    {
      public static final int ID_1 = 1;
      public static final int ID_2 = 2;

      public static int test()
      {
        return 3;
      }
    }
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下看起来编译器正在编译时解决操作.