0

I want to create an instance of Item.class. It takes two objects as constructor parameters.

First FirstObject = new First();
Second SecondObject = new Second();

 Class[] constructorArgs = new Class[]{First.class,Second.class};

 Item.class.getConstructor(constructorArgs).newInstance(FirstObject, SecondObject);

this doesn't seem to work. I get a compiler error that says:

unhandled exception Java.Lang.NoSuchMethodException

How to fix?

Mike James Johnson
  • 724
  • 2
  • 8
  • 29

1 Answers1

2

NoSuchMethodExceptionis a checked exception so you either need to wrap your getConstructor() call in a try-catch block or declare that the method where this code is throws this exception.

try {
    Item.class.getConstructor(constructorArgs).newInstance(FirstObject, SecondObject);
} catch (NoSuchMethodException e) {
  // log the error
  e.printStackTrace();
}
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89