Local caching of Java constants

Let's say I have a Java application that uses the constant (static) int from the library:

int myval = OutsideLibraryClass.CONSTANT_INT;

Now, without recompiling my application, I run it against a slightly different version of OutsideLibraryClass, in which the CONSTANT_INT value is different.

Will my application appear to view the new value (because it selects it at run time) or the old one (because the value is compiled into bytecode in my method)? It doesn't matter if CONSTANT_INT is final? Is there any part of the Java spec that talks about this?

+5
source share
4 answers

, . (JLS 13.1)

+4

, , , . , .

public class Const {
   public static final int CONSTANT;
   static {
      CONSTANT = 4;
   }
}

class Test
{
   int c = Const.CONSTANT;
}

,

public class Const {
   public static final int CONSTANT = 4;
}

class Test
{
   int c = Const.CONSTANT;
}
+2

, . . . .

+1

JVM:

- , static (§2.9.1) , static . (§2.17.2) (§2.5.1). , (§ 2.17.8).

, OutsideLibraryClass ClassLoader, . myVal, OutsideLibraryClass, ClassLoader. , JVM, jar, OutsideLibraryClass, , .

UPDATE

The above statement is true if you are talking about an instance of a local variable in a method. If your variable myVal is declared at the class level, then people who say that this will not change are correct.

+1
source

All Articles