英文:
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 < 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论