Suppose, I want an int[] array to be shared by all instances of enum. Here is an example
public enum SampleEnum {
Enum1(1), Enum2(2), Enum3(3), Enum4(4);
private int[] values;
private static final int[] SharedValues = {1, 2, 3, 4, 5};
private static final int ValueCount = SharedValues.length;
private SampleEnum(int factor) {
// I prefer to calculate data once within constructor
values = new int[ValueCount];
for (int i=0; i<ValueCount; i++)
values[i] = SharedValues[i] * factor;
}
private int[] getValues() {
return values;
}
}
Guess what: I get message "Cannot refer to the static enum field within an initializer" for both ValueCount and SharedValues.
The problem can be overcome by placing the static array in a separate class:
class SampleEnumData {
static final int[] SharedValues = {1, 2, 3, 4, 5};
}
public enum SampleEnum {
Enum1(1), Enum2(2), Enum3(3), Enum4(4);
private int[] values;
private SampleEnum(int factor) {
// I prefer to calculate data once within constructor
int[] sharedValues = SampleEnumData.SharedValues;
int valueCount = sharedValues.length;
values = new int[valueCount];
for (int i=0; i<valueCount; i++)
values[i] = sharedValues[i] * factor;
}
private int[] getValues() {
return values;
}
}
But this looks more as an awkward patch, than a logical solution.
It there a reason for not allowing a reference to a static class within enum initializer?