[SOLVED] Instantiating a particular class constructor using reflection

I guess that’d be as easy as replacing all the Inner types in my sketch w/ AbstractExp: :thinking:

void setup() {
  final Class<?> appCls = getClass(), innerCls;
  try {
    innerCls = Class.forName(appCls.getName() + '$' + "AbstractExp"); // replaced
  }
  catch (final ClassNotFoundException ex) {
    throw new RuntimeException(ex);
  }
  println(innerCls, ENTER);

  final AbstractExp[] inners = new AbstractExp[2]; // replaced
  try {
    inners[0] = (AbstractExp) innerCls.getDeclaredConstructor(appCls) // replaced
      .newInstance(this);

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

  exit();
}

class AbstractExp { // replaced
  String msg = " Constructor";

  AbstractExp() { // replaced
    msg = "Empty" + msg;
  }

  AbstractExp(final String txt) { // replaced
    msg = txt + msg;
  }

  @Override String toString() {
    return getClass().getName() + TAB + TAB + msg;
  }
}
2 Likes