Re: Idiom for forcing class loading?
On 18 Nov, 20:06, Tom Anderson <t...@urchin.earth.li> wrote:
On Wed, 18 Nov 2009, Peter Duniho wrote:
Tom Anderson wrote:
[...]
Am i right in thinking that all of these will force loading of Foo?
I think so. But I haven't checked the spec to make sure.
Does anyone have any other idioms? How about any opinions on which idi=
om is
best, or at least most idiomatic?
I find the question ironic. :) The fact is, you've got some clear=
ly
non-idiomatic scenario, where for some reason your code has managed to =
become
dependent on the initialization of a class that it does not in fact ref=
er to
in the process of being dependent on it.
Given that violation of a very fundamental assumption one normally coul=
d make
in a Java program, asking for an idiomatic solution to the violation se=
ems
sort of silly to me. Your code is already broken; any work-around is
destined to be non-idiomatic. :)
What's really happening is more like this:
class FooMangler implements Mangler {
static {
ManglerRegistry.register("foo", FooMangle=
r.class);
}
}
class ManglingParser extends org.xml.sax.helpers.DefaultHandler {
public void startElement (String uri, String localName, S=
tring qName, Attributes attrs) throws SAXException {
String manglerName = attrs.getValue("ma=
ngler");
Mangler mangler = ManglerRegistry.looku=
p(manglerName);
mangler.mangle(qName, attrs);
}
}
The idea is that manglers can take care of registering themselves - as
long as they're loaded. This is an old and fairly well-known pattern (at
least, not wildly obscure - in terms of birds, about as common as a
kingfisher is in England), although i certainly wouldn't say it's a good
one, or even a non-dubious one. 'Broken' is a bit too strong, although
only a bit.
If you have control on the source code of the mangler, I would do like
this:
class FooMangler implements Mangler {
public static void autoregister() {}
...
}
and to initialize it, FooMangler.autoregister();
else, Class.forName(FooMangler.class.getName()) is the safest bet: it
always initializes the class and fails at compile time if FooMangler
is ever renamed (provided that the file containing the Class.forName
is recompiled!).
Alessio