2

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 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

I tried that and it said: CandyTester.java:19: error: method newInstance in class Class<T> cannot be applied to given types and the reason was actual and formal argument lists differ in length
Try candyClass.getDeclaredConstructor(Double.class).newInstance(...). This should work.
I tried that and I got a different error this time: CandyTester.java:19: error: incompatible types: Object cannot be converted to Candy and it also said Note: CandyTester.java uses unchecked or unsafe operations.
All the classes must be a subclass of Candy, if you want to store it in a List<Candy>. Using Reflection will give you that kind of note, because using methods of this package is unsafe.
Thank you for your help!! I casted it to Candy to avoid that error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.