How to instantiate class from String?

Hello,
Hope the following information will help …

I’m using a factory pattern to create different polygon instances.
The polygons inherit an abstract class.

// Define this global variables
Class self;
 // if your sketch is called sample.pde, use sample as type for that
sample that;

// Add this to your sketch setup()
self = getClass();
that = this;

// The abstract class from which all polygons will inherit
abstract class Shape {
    float x = 0; float y = 0;
    Shape(String type, float _x, float _y) {
      this.x = _x;
      this.y = _y;
    }
}

// The classes for the different polygons
class ShapeA extends Shape {
  ShapeA(float x, float y) {
    super("ShapeA", x, y);
  }
}
class ShapeB extends Shape {
  ShapeB(float x, float y) {
    super("ShapeB", x, y);
  }
}
...
// Probably the most important. 
// Create instances based on the class name
class Factory {
  Shape newShape(String type, float x, float y) {
    Shape shape = null;
    try {
      Class<?> shapeClass = Class.forName(self.getName() + "$" + type);
      Constructor<?>[] constructors = shapeClass.getDeclaredConstructors();
      Constructor instance = constructors[0]; // use first constructor
      instance.setAccessible(true);
      shape = (Shape) instance.newInstance(that, x, y);  
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    } 
    catch (Exception e) {
      e.printStackTrace();
    }
}

// Create an instance using the class name
shape = factory.newShape("ShapeA", x, y);
2 Likes