Java static final values replaced in code when compiling?

后端 未结 10 1303
死守一世寂寞
死守一世寂寞 2020-11-28 10:27

In java, say I have the following

==fileA.java==
class A
{  
    public static final int SIZE = 100;
}  

Then in another file I use this valu

10条回答
  •  佛祖请我去吃肉
    2020-11-28 11:28

    Another route to proving that the behavior is to looking at the generated bytecode. When the constant is "small" (presumably < 128):

    public B();
      Code:
       0:   aload_0
       1:   invokespecial   #10; //Method java/lang/Object."":()V
       4:   aload_0
       5:   bipush  42
       7:   anewarray       #3; //class java/lang/Object
       10:  putfield        #12; //Field temp:[Ljava/lang/Object;
       13:  return
    
    }
    

    (I used 42 instead of 100 so it stands out more). In this case, it is clearly substituted in the byte code. But, say the constant is "bigger." Then you get byte code that looks like this:

    public B();
      Code:
       0:   aload_0
       1:   invokespecial   #10; //Method java/lang/Object."":()V
       4:   aload_0
       5:   ldc     #12; //int 86753098
       7:   anewarray       #3; //class java/lang/Object
       10:  putfield        #13; //Field temp:[Ljava/lang/Object;
       13:  return
    

    When it is bigger, the opcode "ldc" is used, which according to the JVM documentation "an unsigned byte that must be a valid index into the runtime constant pool of the current class".

    In either case, the constant is embedded into B. I imagine, since that in opcodes you can only access the current classes runtime constant pool, that this the decision to write the constant into the class file is independent of implementation (but I don't know that for a fact).

提交回复
热议问题