一、illegal forward refrence
前天写一个类时遇到一个很眼生的编译错误(问题简化后):
1
punlic final
class
Constants
{
2
public static int VAR2 = VAR1 + 1;
3
public static int VAR1 = 1;
4
}
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
![dot.gif](/Images/dot.gif)
2
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
3
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
4
![ExpandedBlockEnd.gif](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
编译时出错(第2行):
illegal forward refrence
仔细一想,是因为VAR2引用的VAR1在VAR2之后定义,看来在Java中定义static变量时应遵循“声明先于使用”的原则。
二、static块
还是上一个类,VAR1和VAR2定义成final,值存在一个properties文件中,在使用前必须将值load进来:
System.getProperties().load(new FileInputStream("constants.properties"));
于是将上面的代码放在static块中:
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
![dot.gif](/Images/dot.gif)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![ContractedSubBlock.gif](/Images/OutliningIndicators/ContractedSubBlock.gif)
![dot.gif](/Images/dot.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockEnd.gif](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedBlockEnd.gif](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
但在运行时VAR1和VAR2没有被赋值,debug后发现static块根本没有执行。于是顿悟:final变量在编译时便被编译器计算、赋值,因此在运行时没有必要执行static块。