Re: Idiom for forcing class loading?
Tom Anderson wrote:
We have a class which does some setup in a static block that needs to
happen early in the lifecycle of the app (this is a dubious design, but
there you go - it's largely forced on us from without). Thus, it needs to
get loaded early. We have an initialiser class which runs at a suitable
time, so that's where we'll load the class. What's the best way to do
this?
....
I could just store it in a local:
void initialise() {
Class foo = Foo.class;
}
Since i [sic] actually have several classes, i [sic] could put them in an=
array:
void initialise() {
Class[] loadedClasses = new Class[] {Foo.class, Bar.cla=
ss, Baz.class};
}
Am i [sic] right in thinking that all of these will force loading of Foo?
Yes, but not initialization. If all you need is loading, you're fine,
but if you need initialization, you're not..
Mere reference to the 'class' literal is forbidden to initialize the
class. JLS 12.4.1
<http://java.sun.com/docs/books/jls/third_edition/html/
execution.html#12.4.1>
This restriction is enforced in Sun JVMs starting with Java 5.
'Class.forName( String )' is documented to cause initialization but
'Class#getName()' is not so documented.
<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#forName
(java.lang.String)>
<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getName()>
It may be, however, that the latter is one of the "certain reflective
methods in class Class" to which the JLS refers, but without explicit
documentation of such it's a fragile promise/premise.
--
Lew