[SOLVED] Instantiating a particular class constructor using reflection

The old sketch only had an inner class called Inner w/ an empty constructor:

class Inner {
  @Override String toString() {
    return getClass().getName();
  }
}

However, your class now also got a constructor w/ a String parameter:

So you’re gonna need to request that when you invoke the method Class::getDeclaredConstructor():
Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getDeclaredConstructor(java.lang.Class...)

Plus, pass the String argument when invoking the method Constructor::newInstance():
Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)

Here’s a more updated version of my old sketch I did for you back then:

/**
 * Reflexive Inner Class Instantiation (v3.0)
 * GoToLoop (2019/Jan/30)
 *
 * https://Discourse.Processing.org/t/
 * instantiating-a-particular-class-constructor-using-reflection/7968/6
 *
 * https://Forum.Processing.org/two/discussion/27164/
 * string-to-class-classnotfoundexception#Item_5
 */

void setup() {
  final Class<?> appCls = getClass(), innerCls = appCls.getDeclaredClasses()[0];
  println(innerCls);

  final 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);

  exit();
}

class Inner {
  String msg = " Constructor";

  Inner() {
    msg = "Empty" + msg;
  }

  Inner(final String txt) {
    msg = txt + msg;
  }

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