爪哇 - 返回一个类(阵列)的一个实例 [英] java - return an instance of a class (array)

查看:118
本文介绍了爪哇 - 返回一个类(阵列)的一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有类数组的形式:

So I have an array of classes:

Class<?>[] classes;

和我填充该班在我的构造函数:

And I populate that classes in my constructor:

public Sample (Class<?>[] classes){
this.classes = classes;
}

然后,我有一个返回根据他们的指数类的一个实例的方法:

Then, I have a method that returns an instance of one of the classes depending on their index:

public Object getInstanceOfClassWithIndex(int index){
   return new classes[index];
}

不幸的是,这并不工作,导致编译错误。谢谢。任何帮助将是AP preciated。

Unfortunately that doesn't work and causes a compile error. Thanks. Any help would be appreciated.

推荐答案

您应该调用的的newInstance()方法一个给定的索引创建该类的对象。

You should call the newInstance() method to create an object of the class at a given index.

return classes[index].newInstance();

这篇关于爪哇 - 返回一个类(阵列)的一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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