午夜拍键惊奇
子夜 编程 代码与我同在
posts - 48,comments - 118,trackbacks - 79

一、illegal forward refrence

前天写一个类时遇到一个很眼生的编译错误(问题简化后):

1punlic final class Constants{
2  public static int VAR2 = VAR1 + 1;
3  public static int VAR1 = 1;
4}

编译时出错(第2行):

illegal forward refrence

仔细一想,是因为VAR2引用的VAR1在VAR2之后定义,看来在Java中定义static变量时应遵循“声明先于使用”的原则。

 

二、static块

还是上一个类,VAR1和VAR2定义成final,值存在一个properties文件中,在使用前必须将值load进来:

System.getProperties().load(new FileInputStream("constants.properties"));

于是将上面的代码放在static块中:

punlic final class Constants{
  
static{
    System.getProperties().load(
new FileInputStream("constants.properties"));
  }


  
public static final int VAR2 = System.getProperties().getProperty("var2");

  
public static final int VAR1 = System.getProperties().getProperty("var1");
}


但在运行时VAR1和VAR2没有被赋值,debug后发现static块根本没有执行。于是顿悟:final变量在编译时便被编译器计算、赋值,因此在运行时没有必要执行static块。

posted on 2005-08-04 12:27 ^ Mustang ^ 阅读(507) 评论(0)  编辑  收藏 所属分类: Java 点滴

只有注册用户登录后才能发表评论。


网站导航: