OK the version below works with inner classes so should solve the creation problem and access to Processing methods.
import java.lang.reflect.*;
import java.util.*;
GameCharacter player;
public void setup() {
size(400, 300);
player = new PlayerCharacter();
player.addToInventory(this, VanillaIceCream.class);
player.addToInventory(this, IceCream.class);
// List players inventory
player.printInventory();
}
public class GameCharacter {
protected Inventory invt = new Inventory();
public GameCharacter() {
}
public void addToInventory(PApplet papp, Class<? extends Ingredient> type) {
invt.add(papp, type);
}
public void printInventory() {
invt.printInventory();
}
}
public class PlayerCharacter extends GameCharacter {
public PlayerCharacter() {
}
// other methods...
}
public class Inventory {
protected List<Ingredient> items = new ArrayList<Ingredient>();
public Inventory() {
}
public void add(PApplet papp, Class<? extends Ingredient> type) {
try {
Ingredient ingredient = null;
Class<?>[] innerClasses = papp.getClass().getDeclaredClasses();
for (Class<?> innerClass : innerClasses) {
if (innerClass == type) {
Constructor<? extends Ingredient> cstr = type.getDeclaredConstructor(papp.getClass());
ingredient = cstr.newInstance(papp);
break;
}
}
// do stuff with ingredient
items.add(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 class Ingredient {
public Ingredient() {
}
public void print() {
println("Ingredient");
}
// other methods
}
public class IceCream extends Ingredient {
IceCream() {
}
public void print() {
println("Icecream");
}
}
public class VanillaIceCream extends IceCream {
VanillaIceCream() {
}
public void print() {
println("Vanilla Icecream");
}
}