2011-10-17 103 views
4

我需要從類對象的數組,像這樣創建一個類的新實例:從類對象構造類的實例在Java中

static Class[] spells = {Fireball.class, Iceball.class}; 

所以,當我想打電話給火球我應該能夠這樣做

Spell Currentspell = new spells[0](posx, posy); 

火球和冰球是拼寫的方式子類。

我該怎麼做?

謝謝你的問候。

+1

這可能是你最好告訴我們你想實現而不是什麼代碼,什麼樣的影響你」目前正在使用來嘗試實現它。一旦我們知道這一切是什麼,可能有更乾淨的方式來做這一切。當我在通常不需要執行此操作的應用程序中大量使用反射時,我的代碼味道雷達總是會上升。 –

回答

9
Constructor constructor = spells[0].getConstructor(int.class, int.class); 
Spell Currentspell = (Spell)constructor.newInstance(posx, posy); 
+0

我試圖這樣做: '嘗試構造函數= spells [0] .getConstructor(Integer.class,Integer.class); Spell Currentspell =(Spell)constructor.newInstance(100,100); catch(Throwable e){ System.err.println(e); }' 但它不會給我一個錯誤或創建類實例 –

+0

@KristofferDorph是'Currentspell'實例null?嘗試捕捉'Exception e'而不是'Throwable e'。另外,你可以發佈你試圖使用的'Fireball'的構造函數嗎? –

+0

非常感謝,讓它工作! :-)是我的一個小錯誤,但你解決了它,謝謝一堆! –

0

那麼,一方面,你會想要縮小可以存儲在你的數組中的類的類型。其次,你的實例代碼是關閉的。沒有進入閹這是實現這一目標的最佳方式,這裏是一些(最好)代碼:

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