So I want to do something like this, where you add a new instance of a class determined by a variable (trust me, I have a good reason for this, but I can’t tell…)
Class type;
dummy1 list[] = new dummy1[3];
void setup() {
type = dummy2.class;
list[0] = new type;
type = dummy3.class;
list[1] = new type;
}
class dummy1 {}
class dummy2 extends dummy1 {}
class dummy3 extends dummy1 {}
This (obviously) doesn’t work… I am wondering if there is a different correct way to do this. Apologies if the answer is easy and I am just dumb
// https://Discourse.Processing.org/t/
// how-do-you-choose-what-class-you-add-to-a-list-with-a-variable/22987/3
// GoToLoop (2020/Aug/02)
static final int DUMB = 0, DUMMY = 1, DUMBER = 2;
int dumbType;
void draw() {
dumbType = (int) random(3);
final Dumb d = getDumb(dumbType);
print(d, TAB);
noLoop();
background((color) random(#000000));
}
void mousePressed() {
redraw();
}
Dumb getDumb(final int which) {
switch (which) {
case DUMB:
return new Dumb();
case DUMMY:
return new Dummy();
case DUMBER:
return new Dumber();
default:
throw new RuntimeException("Unknown Dumb Type Value!");
}
}
class Dumb {
@Override String toString() {
return getClass().getSimpleName();
}
}
class Dummy extends Dumb {
}
class Dumber extends Dumb {
}
@GoToLoop This is a valid answer, (I had thought of this myself) but I want to avoid having a big switch statement. My question was kind of vague, but to clarify I have a lot of classes, and don’t want to do this, but I will if I have to.
You can replace that w/ Class::getDeclaredConstructor() + Constructor::newInstance():
- Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getDeclaredConstructor(java.lang.Class...)
- Constructor (Java SE 11 & JDK 11 )
I’m basing this new alternative version from these 2 old forum threads:
- String to Class: ClassNotFoundException - Processing 2.x and 3.x Forum
- [SOLVED] Instantiating a particular class constructor using reflection - Coding Questions - Processing Foundation
// https://Discourse.Processing.org/t/
// how-do-you-choose-what-class-you-add-to-a-list-with-a-variable/22987/5
// GoToLoop (2020/Aug/02)
static final Class[] dumbClasses = {
Dumb.class, Dummy.class, Dumber.class
};
final Class<? extends PApplet> sketchClass = getClass();
void draw() {
final Class<Dumb> dumbClass = dumbClasses[(int) random(dumbClasses.length)];
final Dumb d = getDumb(dumbClass);
print(d, TAB);
noLoop();
background((color) random(#000000));
}
void mousePressed() {
redraw();
}
<T> T getDumb(final Class<T> dumbClass) {
try {
return dumbClass.getDeclaredConstructor(sketchClass).newInstance(this);
}
catch (final ReflectiveOperationException e) {
System.err.println(e);
return null;
}
}
class Dumb {
@Override String toString() {
return getClass().getSimpleName();
}
}
class Dummy extends Dumb {
}
class Dumber extends Dumb {
}