java - Instantiate an extended class or its parent (depending on circumstances) -
let's have class named human
in projecta
. instantiated in creaturebuilder
class of same project.
now want create new class called cyborg
in different project, i.e. in projectb
. projectb
has projecta
in imports, projecta
knows nothing projectb
.
cyborg extends human
, , must instantiated creaturebuilder
of projecta
(so, cyborg
located in projectb
, call creaturebuilder
projectb
instantiate cyborg
, creaturebuilder
located in projecta
, human
class).
i need logic create human
when creaturebuilder
instantiated projecta
, , create cyborg
when creaturebuilder
instantiated projectb
.
i think achievable creating interface getcreature()
method in projecta
. method overridden in projectb
return new cyborg
, passed creaturebuilder
of projecta
. other suggestions? think best workaround? can use reflection api instead?
cheers!
java 8
creaturebuilder
can delegate creature's creation caller asking supplier.
public class creaturebuilder { public creature getcreature(supplier<creature> creaturesupplier) { //do unknown things return creaturesupplier.get(); } }
usage projecta
public class projecta { public static void main(string[] args) { creature = new creaturebuilder().getcreature(human::new); } }
usage projectb
public class projectb { public static void main(string[] args) { creature b = new creaturebuilder().getcreature(cyborg::new); } }
and never use reflection if you're not forced to.
java 7
if you're sticked java 7, principle remains same except it's bit more verbose.
you have declare , use own supplier-like interface
public interface creaturesupplier { creature get(); } public class creaturebuilder { public creature getcreature(creaturesupplier creaturesupplier) { //do things return creaturesupplier.get(); } }
usage bit more verbose
public class projecta { public static void main(string[] args) { creature = new creaturebuilder().getcreature(new creaturesupplier() { @override public creature get() { return new human(); } }); } } public class projectb { public static void main(string[] args) { creature b = new creaturebuilder().getcreature(new creaturesupplier() { @override public creature get() { return new cyborg(); } }); } }
and... that's it, you've got same behaviour 1 in java 8.
Comments
Post a Comment