Calling the constructor without knowing the name of the class (java) -


this problem easier understand code words:

map<integer, parent> objectmap = new hashmap<integer, parent>();  parent myparent; child1 mychild1; child2 mychild2; //a lot more mychilds  objectmap.put(1, mychild1); objectmap.put(2, mychild2); //place mychilds  mychild1 = new child1();  //constructor expensive, object may not used mychild2 = new child2();  //constructor expensive, object may not used //call constructor of mychilds  parent finalobject;  int number = 1; //this can number  finalobject = objectmap.get(number); 

as see, don't know in advance class finalobject be. code works without problem, here question:

how can avoid calling both constructors?

as mychild1 or mychild2 used , constructor methods quite expensive, want call 1 used.

something like

finalobject.callconstructor(); 

in last line

any ideas?

thanks in advance.

edit: want know how call constructor without knowing name of class. check updated code.

how this?

parent finalobject;  if (condition) {     finalobject = new child1(); } else {     finalobject = new child2(); } 

or, better, this?

parent finalobject = condition? new child1() : new child2(); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -