java - Is there a difference between initializing a variable with its declaration, or in a static initialization? -
the static initializer called once classloader, want, doing initialization outside static code block more readable (debatable). there difference between two?
private static final map<myenum, cheese> cheesecache; static { parsercache = new enummap< myenum, string>(myenum.class){{ for(myenum myenum: myenum.values()){ put(myenum, new cheese(myenum)) ; } }}; }
or :
private static final map<lab, labresultparser> cheesecache = new enummap< myenum, string>(myenum.class){{ for(myenum myenum: myenum.values()){ put(myenum, new cheese(myenum)) ; } }};
it can affect ordering - example have:
private static final int declaredfirst; private static final int declaredsecond = new random.nextint(); static { declaredfirst = declaredsecond + 1; }
the initializers executed in textual order. of course, have declared declaredfirst
second:
private static final int declaredsecond = new random.nextint(); private static final int declaredfirst = declaredsecond + 1;
personally use static initialization blocks can't cleanly express initial value in single expression.
oh, , if initialize in static initialization block, variable can't treated constant expression:
private static final int this_is_a_constant = 10; private static final int thisisnotaconstant; static { thisisnotaconstant = 20; } public static void main(string[] args) { system.out.println(this_is_a_constant); // 10 inlined system.out.println(thisisnotaconstant); // 20 not inlined }
that's relevant, of course.
so in most cases it's personal choice. of course in case, ability use more statements means don't need use ugly (imo) "anonymous inner class initialization":
private static final map<myenum, cheese> cheesecache; static { parsercache = new enummap<>(myenum.class); (myenum myenum: myenum.values()) { put(myenum, new cheese(myenum)); } }
Comments
Post a Comment