[SOLVED] Instantiating a particular class constructor using reflection

Actually, I ran into another problem.

Everything works fine if that code stays in setup().

But when I incorporate that bit of code into my Wallpaper class I get a classNotFound exception: sketch_190130a$Wallpaper$AbstractExp.

Of course, because in the cmd Class<?> appCls = getClass(), innerCls; getClass() refers to the WallPaper class.

But if I change the line to Class<?> appCls = PAPPLET.getClass(), innerCls; I get an argument type mismatch with the command
contents = (Contents) innerCls.getDeclaredConstructor(appCls, String.class).newInstance(this, "Test");

So how do I fix this?

Update: Actually, I just figured it out.

contents = (Contents) innerCls.getDeclaredConstructor(appCls, String.class).newInstance(PAPPLET, "Booyah");

I need the class as the first parm in the newInstance method… Makes sense…

Just for posterity, here’s the final Wallpaper class code:

class Wallpaper {
  
  Contents contents;
  
  Wallpaper(String design, String pattern){
    
    println("Wallpaper: celldesign:",design,"pattern:",pattern);
    
    contents = null;
    
    final Class<?> appCls = PAPPLET.getClass(), innerCls;
    try {
      innerCls = Class.forName(appCls.getName() + '$' + design);
      contents = (Contents) innerCls.getDeclaredConstructor(appCls, String.class).newInstance(PAPPLET, pattern);
    }
    catch (final ReflectiveOperationException ex) {
      //System.err.println(ex);     
      throw new RuntimeException(ex);
    } 

    // just for dev testing
    println("hello");
    contents.printPattern(); 
  }
}

Thanks again, GoToLoop, for your help.

2 Likes