Constant won't change after class replaced in Tomcat
I have deployed a application on Tomcat 6 and after I deployed I wanted to do some changes on my constant class and I uploaded only the constant class (.class
file) into 开发者_StackOverflowexploded war file.
And even after I restart the server several times the changes I made wouldn't show.
All I changed was some strings in constants. What would you suggest me to do other than uploading war file again?
You will have to recompile all classes that reference those String
constants.
Note that a static final
field of a primitive type or of type String
that is initialized with a compile time constant value (a so called constant variable) will be inlined when they are used in other classes.
In other words if you have these classes:
public class Constants {
public static final int FOO = 42;
}
public class Bar {
public void frobnicate() {
System.out.println(Constants.FOO);
}
}
Then at compile time the value of FOO
will be compiled into the .class
file of Bar
, meaning that Bar
no longer references Constants
at runtime!
This also means that any change of FOO
will have no effect on Bar
until you re-compile Bar
with the new Constants.class
.
This effect is discussed at length in JLS §13.4.9 final
Fields and Constants.
One way to avoid this problem in the future is to ensure that your "constants" are not interpreted as constant variables by the compiler. One way to do this is to move the assignment of a value from an initializer to a simple assignment via a static initializer block:
public class Constants {
public static final int FOO;
static {
FOO = 42;
}
}
精彩评论