5

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.

1
  • 1
    It may be better for you to tell us what effect you're trying to achieve rather than what code you're currently using to try to achieve it. There may be a cleaner way of doing all this, once we know what all this is. My code smell radar always goes up when I see heavy use of reflection in an application that typically doesn't need to do this. Commented Oct 17, 2011 at 23:40

4 Answers 4

11
Constructor constructor = spells[0].getConstructor(int.class, int.class);
Spell Currentspell = (Spell)constructor.newInstance(posx, posy);
Sign up to request clarification or add additional context in comments.

3 Comments

I'm trying to do this: try { Constructor constructor = spells[0].getConstructor(Integer.class, Integer.class); Spell Currentspell = (Spell)constructor.newInstance(100, 100); } catch (Throwable e) { System.err.println(e); } But it doesn't give me an error or create the class instance
@KristofferDorph is Currentspell instance null? try catching Exception e rather than Throwable e. Also, can you post the constructor for Fireball that you are trying to use ?
Thanks alot, got it working! :-) Was a little mistake from my part, but you solved it, thanks a bunch!
1

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/

Comments

0

You use the getConstructor() method to get the specific constructor you want and then call newInstance() on the constructor object.

Comments

0

Well, for one thing you will want to narrow down the type of class that can be stored in your array. And second, your instantiation code is off. Without going into wether this is the best way to accomplish this, here is some (better) code:

static Class<Spell>[] spells = new Class<Spell>[] { Fireball.class, Iceball.class };
Spell currentSpell = spells[someIndex].newInstance();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.