Processing wraps your sketch code inside a class named after the sketch so all your classes are inner classes. To instantiate an inner class using reflection requires an instance of the enclosing class.
The easiest solution is to make all your classes top-level by declaring them public static but it will mean they cannot directly access variables declared ‘globally’ in the main sketch. You would have to pass them as parameters to the class methods, which is good practice anyway.
So I have created a sketch based on my comments that should help.
import java.lang.reflect.*;
import java.util.*;
GameCharacter player;
public void setup() {
size(400, 300);
player = new PlayerCharacter();
player.addToInventory(VanillaIceCream.class);
player.addToInventory(IceCream.class);
// List players inventory
player.printInventory();
}
public static class GameCharacter {
protected Inventory invt = new Inventory();
public GameCharacter() {
}
public void addToInventory(Class<? extends Ingredient> type) {
invt.add(type);
}
public void printInventory() {
invt.printInventory();
}
}
public static class PlayerCharacter extends GameCharacter {
public PlayerCharacter() {
}
}
public static class Inventory {
protected List<Ingredient> items = new ArrayList<Ingredient>();
public Inventory() {
}
public void add(Class<? extends Ingredient> type) {
try {
Constructor<? extends Ingredient> cstr = type.getDeclaredConstructor();
Ingredient ingredient = cstr.newInstance();
items.add(ingredient);
// do stuff with ingredient
}
catch (NoSuchMethodException e) {
e.printStackTrace();
println("Constructor not available: " + e.getMessage());
}
catch (IllegalAccessException e) {
println("Constructor can not be accessed: " + e.getMessage());
}
catch (InvocationTargetException e) {
println("Exception in constructor: " + e.getCause().getMessage());
}
catch (InstantiationException e) {
println("Class cannot be instantiated: " + e.getMessage());
}
}
public void printInventory() {
for (Ingredient item : items)
item.print();
}
}
public static class Ingredient {
public Ingredient() {
}
public void print() {
println("Ingredient");
}
}
public static class IceCream extends Ingredient {
IceCream() {
}
public void print() {
println("Icecream");
}
}
public static class VanillaIceCream extends IceCream {
VanillaIceCream() {
}
public void print() {
println("Vanilla Icecream");
}
}