Java中变化无常的常量

Java中变化无常的常量

问题:
第一版:
直接编译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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值