Re: Idiom for forcing class loading?
On Wed, 18 Nov 2009, markspace wrote:
Tom Anderson wrote:
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?
Well, rule #1 is "if it ain't broke don't fix it", so this whole
enterprise is dubious to me.
Son, you may wish to look into getting a new rule provider. If it ain't
broke but it's smelly, it's going to break, so fix it now before it does.
However, I don't see why these classes won't be loaded in any of the
examples you presented. The only issue I see is that an optimizer may
decide that the objects are "not used" and optimize them away. That is,
actually remove the statements referencing the classes.
Since class loading is side-effectual, i don't think an optimiser is free
to do that. Although i admit i'm a bit shaky about the rules on this.
Thus you might want to actually do something with the classes:
void initialise() {
Class[] loadedClasses = new Class[] {Foo.class, Bar.class, Baz.class};
Logger logger = Logger.getLogger( "x" );
for( Class c : loadedClasses ) {
logger.config( "Loaded class: "+c.getName() );
}
}
Replace "x" with the class name in which initialise() is declared.
This may also be bonkers, but it's a safe kind of bonkers, I think.
It at least makes it look like something useful is being done, which is
what matters!
I also considered:
void initialise() {
loadClass(Foo.class);
}
void loadClass(Class cl) {
// do nothing!
}
!
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