创建一个类的数组,然后从这些类实例化对象。

huangapple go评论81阅读模式
英文:

Create an array of classes and then instantiate objects from them

问题

我想创建一个类的数组,然后遍历该数组并从数组中的每个类实例化对象。

我尝试了以下内容:

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));
    }
}

然后我得到了这个错误:

CandyTester.java:19: 错误: 找不到符号
                candyList.add(new candyClass(r.nextDouble() + 0.1 * 20));
                                  ^
  符号:   类 candyClass
  位置: 类 CandyTester
1 个错误

我不太清楚从这里开始该怎么办,因为我不太确定 Java 类与对象之间的关系。

英文:

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 &lt; 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.

答案1

得分: 1

使用方法 newInstance(args),该方法使用特定的构造函数实例化了一个新的对象。

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

Use the method newInstance(args), which instantiates a new object of your class using a specific constructor.

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

huangapple
  • 本文由 发表于 2020年3月16日 10:34:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/60699684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定