I need to use reflection to create a new instance of a non-static class of type unknown at runtime. Code and error messages are below. The class will always be of some type that extends the abstract class Formula. In the code below, DucksJ is a class that extends the abstract class Formula. A field in the class Parameter is Parameter.formula, of type Formula. The enclosing class for Formula is Basic_fractal_1_0 (I think--at any rate, that is the name of the Processing sketch that contains the class). Any help will be greatly appreciated--thank you!
/* constructor for public class Parameter */
public Parameter(JSONObject param) {
Object[] parameters = new Object[];
// some code that loads variables of multiple types into parameters
String className = ("Basic_fractal_1_0$" + param.getString("Formula Type"));
Class<?> innerClass = Class.forName(className);
Class<?> outerClass = Class.forName("Basic_fractal_1_0");
System.out.println(innerClass);
System.out.println(outerClass);
Constructor con = innerClass.getDeclaredConstructors()[0];
System.out.println(con);
try {
this.formula = (Formula)con.newInstance(parameters);
} catch (Exception e) {
System.out.println(e.toString());
}
// some additional code
}
When I run this, output is as follows:
class Basic_fractal_1_0$DucksJ
class Basic_fractal_1_0
public Basic_fractal_1_0$DucksJ(java.lang.Object[])
java.lang.IllegalArgumentException: wrong number of arguments
After looking at suggestions here and similar
https://github.com/processing/processing/issues/3446 How to instantiate a non-static inner class with reflection in Java?)
I also tried:
... try {
this.formula = con.newInstance(sketchClass);
} catch (Exception e) ...
This leads to java.lang.IllegalArgumentException: argument type mismatch.
I also tried:
... try {
this.formula = con.newInstance(sketchClass, parameters);
} catch (Exception e) ...
I then get java.lang.IllegalArgumentException: wrong number of arguments
If I try Formula f = (Formula)con.newInstance(new outerClass(), parameters), the compiler tells me "The class outerClass does not exist."
I'm not sure if the problem has to do with the way I'm using Constructor.newInstance() or with the fact that Formula is an abstract class or both. Any suggestions?