7月 132012
らしい。
要するに定数の値を変更しても、それを参照してる側も再コンパイルしないと値が反映されない。
共通ライブラリに定数を定義し、他のプログラムで参照している場合などがヤバイ。
final
なフィールド変数は、値を変更しても、その値を参照している既存バイナリは再コンパイルしない限り新しい値が適用されない。- 定数式で初期化しなくとも、同じ動作となる。
- この動作は条件付コンパイルをサポートした結果の副作用である。
- 定数は絶対に変更されない値でのみ宣言するべき。
- 単に読み込み専用としたい場合は
private static
な変数のgetterのみ宣言する方が良い。 - 定数値を持つ
static final
なフィールドはデフォルト初期値を持つように宣言してはならない。必ず定数式で初期化する。- ×
static final int a;
- ○
static final int a = 0;
- ×
ブランクfinalはインライン展開されない模様。
言語仕様では明確な記述は発見できなかった。
[java]
class Constant1
{
public static final String A;
class Constant1
{
public static final String A;
static
{
A = “test”;
}
}
class Constant2
{
public static final String A = “test”;
}
public class Main
{
public static void main(String[] args)
{
System.out.println(Constant1.A);
//decompile=>System.out.println(Constant1.A)
System.out.println(Constant2.A);
//decompile=>System.out.println(“test”)
}
}
[/java]