I need to create a new instance of a class from an array of class objects like this:
static Class[] spells = {Fireball.class, Iceball.class};
So when I want to call the fireball i should be able to do something like
Spell Currentspell = new spells[0](posx, posy);
Fireball and Iceball is by the way child classes of Spell.
How do i do this?
Thanks in regards.
Constructor constructor = spells[0].getConstructor(int.class, int.class);
Spell Currentspell = (Spell)constructor.newInstance(posx, posy);
You need to invoke the appropriate constructor of the class by reflection.
See the "Creating new objects" section at http://java.sun.com/developer/technicalArticles/ALT/Reflection/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With