Java中变化无常的常量
问题:
第一版:
直接编译UserConstantsTest,编译过程中会检测到UserConstants尚未编译,然后会编译UserConstants
运行结果如图所示:
[img]http://dl.iteye.com/upload/attachment/539574/7fcce2a5-8a0f-37ef-8921-2efbce42691d.png[/img]
第二版:
只修改UserConstants,并且只重新编译UserConstants,得到结果如下图所示:
运行结果如图所示:
[img]http://dl.iteye.com/upload/attachment/539576/a0ab13dd-fb4b-34f3-bdce-940d89749b4d.png[/img]
原因:
[quote] First, true constant variables are inlined.
Second, null is not a constant variable and thus is not inlined and so the actual constant on the classpath is used in that case.[/quote]
Java编译器会讲常数值编译到UserConstantsTest 的指令码或者常量池中,当UserConstantsTest使用这些常量时直接使用保存在类文件中的副本,但是null不是常量值,不受此限。
解决:
第一种:使用get方法来获取常量值
第二种:使用ident方法来获取常量值
参考:
Inconstant Constants in Java:[url]http://www.javaworld.com/community/node/3400[/url]
问题:
第一版:
直接编译UserConstantsTest,编译过程中会检测到UserConstants尚未编译,然后会编译UserConstants
public class UserConstants {
public static final String USER_NAME = "admin";
public static final String PASSWORD = "123456";
public static final String DESCRIPTION = null;
}
public class UserConstantsTest {
public static void main(String[] args) {
System.out.println("User Name: " + UserConstants.USER_NAME);
System.out.println("Password: " + UserConstants.PASSWORD);
System.out.println("Description: " + UserConstants.DESCRIPTION);
}
}
运行结果如图所示:
[img]http://dl.iteye.com/upload/attachment/539574/7fcce2a5-8a0f-37ef-8921-2efbce42691d.png[/img]
第二版:
只修改UserConstants,并且只重新编译UserConstants,得到结果如下图所示:
public class UserConstants {
public static final String USER_NAME = "root";
public static final String PASSWORD = "123456789";
public static final String DESCRIPTION = "This is root account";
}
运行结果如图所示:
[img]http://dl.iteye.com/upload/attachment/539576/a0ab13dd-fb4b-34f3-bdce-940d89749b4d.png[/img]
原因:
[quote] First, true constant variables are inlined.
Second, null is not a constant variable and thus is not inlined and so the actual constant on the classpath is used in that case.[/quote]
Java编译器会讲常数值编译到UserConstantsTest 的指令码或者常量池中,当UserConstantsTest使用这些常量时直接使用保存在类文件中的副本,但是null不是常量值,不受此限。
解决:
第一种:使用get方法来获取常量值
public static final String USER_NAME = "admin";
public static String getUserName () {
return USER_NAME;
}
第二种:使用ident方法来获取常量值
private static String ident(final String constant) {
return constant;
}
public static final String USER_NAME = ident("root");
public static final String PASSWORD = ident("123456789");
public static final String DESCRIPTION = ident("This is root account");
参考:
Inconstant Constants in Java:[url]http://www.javaworld.com/community/node/3400[/url]