从java中的类对象构造类实例
我需要从类对象数组中创建一个类的新实例,如下所示:
static Class[] spells = {Fireball.class, Iceball.class};
因此,当我想调用火球时,我应该能够执行类似
Spell Currentspell = new spells[0](posx, posy);
Fireball 和 Iceball 之类的操作,这是 Spell 的子类。
我该怎么做?
谢谢您的问候。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要通过反射调用该类的适当构造函数。
请参阅 http://java.sun.com/developer 中的“创建新对象”部分/technicalArticles/ALT/Reflection/
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/
您使用
getConstructor()
方法获取你想要的具体构造函数,然后调用newInstance()
。You use the
getConstructor()
method to get the specific constructor you want and then callnewInstance()
on the constructor object.好吧,一方面,您需要缩小可以存储在数组中的类的类型范围。其次,您的实例化代码已关闭。无需考虑这是否是实现此目的的最佳方法,这里有一些(更好的)代码:
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: