0

I might be understanding this wrong, I have multiple classes, for example:

  • Item1
  • Item2
  • Item3

They all extend the same parent class and need the same constructor arguments, I want to be able to call a method like below passing say Item1.class as the parameter, it then returns a new instance of Item1.

private <T extends ParentClass> T getItem(Class<T> itemType) {

After the method has collected the relevant data for the item's constructor, can I use itemType.newInstance() to create a new instance? If so how do I pass arguments to it's constructor?

Quib
  • 1
  • 1
  • Try using a functional interface + method reference instead of a class object. For instance, if the constructors only take a string: `private T getItem(Function constructor)`. You can then call it as `getItem(Item1::new)` etc. If the constructors take two arguments you can use `BiConsumer`, otherwise you can easily create your own functional interface. – Rob Spoor Apr 12 '23 at 11:57

0 Answers0