Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct class instance from class object in java

Tags:

java

class

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.

like image 395
Kristoffer Dorph Avatar asked Oct 17 '11 23:10

Kristoffer Dorph


2 Answers

Constructor constructor = spells[0].getConstructor(int.class, int.class);
Spell Currentspell = (Spell)constructor.newInstance(posx, posy);
like image 97
Bala R Avatar answered Oct 21 '22 03:10

Bala R


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/

like image 28
Thorbjørn Ravn Andersen Avatar answered Oct 21 '22 01:10

Thorbjørn Ravn Andersen