Create an array of classes and then instantiate objects from them

Viewed 72

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 Answers

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