java - Assign to static final field of same name -
to distinguish between instance field , local variable of same name can qualify access field prefix this.:
class test { public final foo x; public test(foo x) { this.x = x; } } i'm trying same thing in static context qualifying access class name:
import java.util.*; class test { public static final map<string,object> map; static { map<string,object> map = new hashmap<>(); // ... // assume fill map useful info here // ... // want freeze , assign field test.map = collections.unmodifiablemap(map); } } the compiler wants nil code. have several variables , of them keeps yelling: "cannot assign value final variable". if don't assign it, complains "variable not initialized" instead. if assign static field @ origin , seek create map unmodifiable afterwards, complains "variable might have been assigned". it's not happy anything.
is flaw in language, or bug in compiler? what's best way crush compiler doing told?
the easiest way solve follows:
import java.util.*; class test { public static final map<string,object> map; static { map<string,object> contents = new hashmap<>(); map = collections.unmodifiablemap(contents); } } somehow seems if qualify constant class name in java 8, compiler won't have it.
update
after more digging, seems java language specification explicitly states simple (unqualified) name needs used assignment of final fields (highlighting mine):
for every access of local variable or blank final field x, x must assigned before access, or compile-time error occurs.
similarly, every blank final variable must assigned @ once; must unassigned when assignment occurs.
such assignment defined occur if , if either simple name of variable (or, field, simple name qualified this) occurs on left hand side of assignment operator.
java
No comments:
Post a Comment