alexander lang writes:
> Does anyone know if one is allowed to initialize static final variables
> within the "try" clause of a static initializer block?
>
> (eg.
> static final int x;
> static{
> try
> {
> x = 5;
> }
> catch(exception e)
> {...and so on ..}
> )
>
> I am working on a software project which has code like this. I am
> getting compile - time error messages which state that I am NOT allowed
> to fo this. Are there some tricks one can use to "trick" the compiler.
> I am assuming that the code previously worked(?). I am using
> jdk1.1.5-glibc.
Final variables must be assigned along all possible execution paths of
the constructor or static initializer block. (Another way of saying
this is that there must not be a way to get through the constructor or
static initializer block without assigning to the final variable.)
Thus, if you assign to the final variable in the try section, you must
also assign it in the catch section.
I haven't looked in the spec to see what happens if a final variable
is assigned a value multiple times. I would imagine that its value is
the last value assigned. If this turns out to be a problem, you can
always do:
static final int x;
static {
int xx;
try {
xx = 5;
...
} catch (...) {
xx = 4;
}
x = xx;
}
Best,
daniel dulitz
Valley Technologies Peak Performance Real-Time DSP
State College, PA