Instantiate one class inside another using a third

Hi. Sorry for my confusing answer.

I just got it working. Thank you for your suggestions – it helped.

I forgot that I needed separate tabs for the PApplet inner classes. So I created separate tabs for each A,B,C.

Here’s the setup:

import java.lang.reflect.*;

final String THISPROC = this.getClass().getCanonicalName();
public final PApplet PAPPLET = this;

void setup(){
  A a = new A();
  a.hello();
}

And here’s the switch command inside C:

      switch(type.getSimpleName()){
        
        case "String"    : println(" is a String");
                           try {
                             field.set(obj, "A happy little string");
                           } catch (Exception e) { }
                           break;
                           
        default           : println(" is custom class:",type.getSimpleName());
                            // somehow magically instantiate A.b = new B();
                            try {
                              Class<?> innerClass = Class.forName(THISPROC + "$" + type.getSimpleName() );
                              Constructor<?> ctor = innerClass.getDeclaredConstructor( PAPPLET.getClass() );
                              Object o = ctor.newInstance(PAPPLET);
                              field.set(obj, o);
                            } catch (InstantiationException e) { println(e);
                            } catch (IllegalAccessException e) { println(e);
                            } catch (ClassNotFoundException e){ println(e);
                            } catch (Exception e) { println(e); }
                            break;
      }
    }

I’m getting a ClassNotFoundException from somewhere, and yet I nevertheless get the string hello from B! in stdout.

So it seems to be working, yet I’m a little mystified that it is…

Update1: Oh, I just figured out why I was getting the exception… The class A itself – ie: this$0 – enters the default switch case… I’ll just ignore it so I don’t get the exception…

Update 2:
Class<?> innerClass = Class.forName(someClass.getTypeName().split("\\$")[0] + "$" + type.getSimpleName() );
can be used instead of
Class<?> innerClass = Class.forName(THISPROC + "$" + type.getSimpleName() );
This eliminates the need for the global variable THISPROC (thus making it easier to compile).

1 Like