从Java中的类对象构造类实例 [英] Construct class instance from class object in java

查看:35
本文介绍了从Java中的类对象构造类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一组这样的类对象创建一个新的类实例:

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和Iceball是Spell的子类.

Fireball and Iceball is by the way child classes of Spell.

我该怎么做?

谢谢.

推荐答案

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

这篇关于从Java中的类对象构造类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆