# How do you choose what class you add to a list with a variable?

**URL:** https://discourse.processing.org/t/how-do-you-choose-what-class-you-add-to-a-list-with-a-variable/22987
**Category:** Coding Questions
**Created:** [August 2, 2020, 1:02pm UTC](https://discourse.processing.org/t/how-do-you-choose-what-class-you-add-to-a-list-with-a-variable/22987 "2020-08-02T13:02:31Z")
**Posts on this page:** 1
**Showing post:** 5

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [August 2, 2020, 8:36pm UTC](https://discourse.processing.org/t/how-do-you-choose-what-class-you-add-to-a-list-with-a-variable/22987/5 "2020-08-02T20:36:48Z")

</div>

> [@no\_spaces](#):
>
> … but I want to avoid having a big `switch` statement.

You can replace that w/ Class::**getDeclaredConstructor()** + Constructor::**newInstance()**: 🚧

1. [Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getDeclaredConstructor(java.lang.Class...)](http://Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getDeclaredConstructor(java.lang.Class...))
2. [Constructor (Java SE 11 & JDK 11 )](http://Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...))

I’m basing this new alternative version from these 2 old forum threads: 🧵

1. [String to Class: ClassNotFoundException - Processing 2.x and 3.x Forum](http://Forum.Processing.org/two/discussion/27164/string-to-class-classnotfoundexception#Item_5)
2. [[SOLVED] Instantiating a particular class constructor using reflection - Coding Questions - Processing Foundation](http://Discourse.Processing.org/t/solved-instantiating-a-particular-class-constructor-using-reflection/7968)

```auto
// 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 {
}

```

---

_[View the full topic](https://discourse.processing.org/t/how-do-you-choose-what-class-you-add-to-a-list-with-a-variable/22987)._
