Idiom for forcing class loading?
Hi chaps,
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?
Before i came to it, the code looked like:
void initialise() {
Class.forName("com.example.Foo");
}
I didn't like that, because it's using a string constant where it could be
using something strongly typed, and so not getting enabling refactoring
and inspection in the IDE. I had a bit of a debate with my pair, and we
changed it to:
void initialise() {
Class.forName(Foo.class.getName());
}
Which works, solves the problem, and is clearly bonkers.
What's a good idiom? One option would be to call a no-op method on the
class literal:
void initialise() {
Foo.class.getName();
}
But that's a bit hackish too. I could just store it in a local:
void initialise() {
Class foo = Foo.class;
}
Since i actually have several classes, i could put them in an array:
void initialise() {
Class[] loadedClasses = new Class[] {Foo.class, Bar.class, Baz.class};
}
Am i right in thinking that all of these will force loading of Foo? Does
anyone have any other idioms? How about any opinions on which idiom is
best, or at least most idiomatic?
Thanks,
tom
--
A hypothesis or theory is clear, decisive, and positive, but it is
believed by no one but the man who created it. Experimental findings,
on the other hand, are messy, inexact things, which are believed by
everyone except the man who did that work. -- Harlow Shapley