Re: Idiom for forcing class loading?
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.
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.
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.