Java static final values replaced in code when com

2019-01-09 01:49发布

In java, say I have the following

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

Then in another file i use this value

==fileB.java==  
import A;
class b
{
      Object[] temp = new Object[A.SIZE];
}

When this gets compiled does SIZE get replaced with the value 100, so that if i were to down the road replace the FileA.jar but not FileB.jar would the object array get the new value or would it have been hardcoded to 100 because thats the value when it was originally built?

Thanks,
Stephanie

10条回答
再贱就再见
2楼-- · 2019-01-09 02:06

Java does optimise these sorts of values but only if they are in the same class. In this case the JVM looks in A.SIZE rather than optimizing it because of the usage case you are considering.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-09 02:11

As an optimization the compiler will inline that final variable.

So at compile time it will look like.

class b
{
      Object[] temp = new Object[100];
}
查看更多
Evening l夕情丶
4楼-- · 2019-01-09 02:11

One thing should note is: static final value is known at compile time if the value is not known at compile time, compiler won't replaces the constant name everywhere in the code with its value.

  public class TestA {
      // public static final int value = 200;
      public static final int value = getValue();
      public static int getValue() {
        return 100;
      }
  }

public class TestB {
    public static void main(String[] args) {
        System.out.println(TestA.value);
    }
}

first compile TestA and TestB, run TestB

then change TestA.getValue() to return 200, compile TestA, run TestB, TestB will get the new value enter image description here

查看更多
Bombasti
5楼-- · 2019-01-09 02:18

You can keep the constant from being compiled into B, by doing

class A
{  
    public static final int SIZE;

    static 
    {
        SIZE = 100;
    }
}  
查看更多
登录 后发表回答