[SOLVED] Instantiating a particular class constructor using reflection

I’ve added your code as is (preserving my previous classes) and I get the error:
ClassCastException: sketch_19013a$AbstractExp cannot be cast to sketch_!90130a$Inner

final PApplet PAPPLET = this;

AbstractExp ae;
Wallpaper wp;
String pattern = "pg";

void setup(){
  
  //ae = new AbstractExp(pattern);
  //ae.printPattern();
  
  //wp = new Wallpaper("AbstractExp", pattern);
  
  Class<?> appCls = getClass();
  Class<?> innerCls = appCls.getDeclaredClasses()[0];
  println("Inner Cls:",innerCls);

  Inner[] inners = new Inner[2];
  try {
    inners[0] = (Inner) innerCls.getDeclaredConstructor(appCls).newInstance(this);

    inners[1] = (Inner) innerCls.getDeclaredConstructor(appCls, String.class).newInstance(this, "String");
  }
  catch (final ReflectiveOperationException ex) {
    System.err.println(ex);
  }
  printArray(inners);
  
}

Update: Actually, I think I’m realizing that I need to instantiate the appCLs with the string name of the class: eg: Class<?> appCls = Class.forName(THISPROC + "$" + "AbstractExp");

Trying that right now…

…getting closer…

Now I get an ArrayIndexOutOfBoundsException: 0 for the innerCls instantiation.

  try {
    Class<?> appCls = Class.forName(THISPROC + "$" + "AbstractExp");
    println("app CLs:",appCls);

    Class<?> innerCls = appCls.getDeclaredClasses()[0];
    println("Inner Cls:",innerCls);
  
    Inner[] inners = new Inner[2];
    try {
      inners[0] = (Inner) innerCls.getDeclaredConstructor(appCls).newInstance(this);
  
      inners[1] = (Inner) innerCls.getDeclaredConstructor(appCls, String.class).newInstance(this, "String");
    }
    catch (final ReflectiveOperationException ex) {
      System.err.println(ex);
    }
    printArray(inners); 
     
  } 
  catch (ClassNotFoundException e) {
    e.printStackTrace();
  } 
1 Like