how to load a java class along with static initializations before they are used? -
i need load classes along their respective static initializations, example, in factory method implementation.
if make reference class using below syntax, jvm not run static initialization part. actually, jvm load classes?
class<shape> shapeclass = shape.class;
or
shape s = null;
but class.forname() execute static initializations. class.forname("shape");
question if way load java class along static initializations? or there other ways? significant performance penalties using class.forname()?
from class.forname(string classname) api: invoking method equivalent to: class.forname(classname, true, currentloader).
the second argument = true means initialize class, , initialize class means run static initializers
this test check
package test; class test2 { static { system.out.println("static init"); } } public class test1 { public static void main(string[] args) throws exception { class.forname("test.test2"); } }
output
static init
but if load test2
class.forname("test.test2", false, classloader.getsystemclassloader());
there no output. can use test see test.class.getname()
not load class either.
the simplest way make load add empty static method , call it:
class test2 { public static void load() { } ... test2.load();
Comments
Post a Comment