Hello again, oh great Java gurus!
I find myself having to instantiate a class from a string using one of its particular constructors. The api for getDeclaredConstructors() indicates this is possible, but the examples I’ve found online of its implementation aren’t clicking for me.
Here’s a stripped-down example of what I’m hoping to achieve.
import java.lang.reflect.*;
// This PApplet processing session //
final String THISPROC = this.getClass().getCanonicalName();
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 Contents {
String pattern;
Contents(){}
Contents(String pattern_){
pattern = pattern_;
}
void printPattern(){ print("pattern is",pattern); }
}
class AbstractExp extends Contents {
AbstractExp(){}
AbstractExp(String pattern_){
super(pattern_);
}
void printPattern(){
super.printPattern();
println(" for AbstractExp");
}
}
class Wallpaper {
Contents contents;
Wallpaper(String design, String pattern){
println("Wallpaper: celldesign:",design,"pattern:",pattern);
contents = null;
try {
Class<?> innerClass = Class.forName(THISPROC + "$" + design);
// Q: How do I call AbstractExp's (String){} constructor with the getDeclaredConstructor method?
// https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredConstructor-java.lang.Class...-
Constructor<?> ctor = innerClass.getDeclaredConstructor( PAPPLET.getClass() );
contents = (Contents) ctor.newInstance(PAPPLET);
println("Wallpaper: class:",design.getClass());
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
And, obviously, I’d like to call innerClass.getDeclaredConstructor( PAPPLET.getClass() );
with my String arg. (This is discussed here.)
Thank you for reading!