最终的静态变量操作,编译还是运行时? [英] Final static variables operations, compile or runtime?

查看:101
本文介绍了最终的静态变量操作,编译还是运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Do final static variables operations happen in run-time or compile time ? For example:

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 ?
}


推荐答案

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

它说:


如果是原始类型或字符串被定义为常量,并且该值在编译时是已知的,编译器将代码中的常量名称替换为其值。

If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value.

因此,一旦完成并且您在方法中以 1 + 2 结束,那么优化它也是合乎逻辑的并且只是使用 3 在编译时。

So once that is done and you end up with 1 + 2 in the method, it would be logical for that to be optimized as well and just use the 3 at compile time.

为了在实践中证明它,你可以编译你的代码,然后将其反编译为看看发生了什么。

To prove it in practice, you can compile your code and then decompile it to see what's going on.

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

I tried with JD-GUI and this is what I got when decompiling your code:

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

      public static int test()
      {
        return 3;
      }
    }

所以看起来在这种情况下编译器正在解决在编译时运行。

So it looks in this case the compiler is solving the operation in compile time.

这篇关于最终的静态变量操作,编译还是运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆