简体   繁体   English

创建一个类数组,然后从它们实例化对象

[英]Create an array of classes and then instantiate objects from them

I want to create an array of classes, then iterate through that array and instantiate objects from each of the classes in that array.我想创建一个类数组,然后遍历该数组并从该数组中的每个类实例化对象。

I tried the following:我尝试了以下方法:

Class[] classes = {Gummy.class, Chocolate.class, Lollipop.class};

for (Class candyClass : classes) {
    for (int i = 0; i < r.nextInt(5); i++) {
        candyList.add(new candyClass(r.nextDouble() + 0.1 * 20));
    }
}

And I got this error:我收到了这个错误:

CandyTester.java:19: error: cannot find symbol
                candyList.add(new candyClass(r.nextDouble() + 0.1 * 20));
                                  ^
  symbol:   class candyClass
  location: class CandyTester
1 error

I don't really know where to proceed from here because I'm not too sure how java class relates to objects.我真的不知道从哪里开始,因为我不太确定 java 类与对象的关系。

Use the method newInstance(args) , which instantiates a new object of your class using a specific constructor.使用方法newInstance(args) ,它使用特定的构造函数实例化您的类的新对象。

Object candy = candyClass.getDeclaredConstructor(Double.class).newInstance(r.nextDouble() + 0.1 * 20);
candyList.add((Candy) candy);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM