Sorry for the cryptic title, but this is difficult to explain. The general rule is that I need a lazy loader that will give me N instances of a bound wildcard type. I’m calling the lazy loader a storage unit.
import java.util.ArrayList;
import java.util.List;
public class StorageUnit<T extends MyInterface> implements Storable<T> {
private int count;
public StorageUnit(int count) {
this.count = count;
}
private List<T> storables = new ArrayList<T>();
public List<T> getInstances(Class<T> c) {
try {
if (storables.size() == 0) {
for (int i = 0; i < count; i++) {
storables.add(c.newInstance());
}
} else {
return storables;
}
}catch (IllegalAccessException illegalAccessException) {
illegalAccessException.printStackTrace();
} catch (InstantiationException instantiationException) {
instantiationException.printStackTrace();
}
return storables;
}
}
Elsewhere in my application I have another class that has a reference to several of these storage units. I need to get instances of the storage unit type, and then I will do something with that type.
import java.util.ArrayList;
import java.util.List;
public class MyStorageUnitContainer {
private List<StorageUnit<? extends MyInterface>> storageUnits;
public MyStorageUnitContainer(List<StorageUnit<? extends MyInterface>> storageUnits) {
this.storageUnits = storageUnits;
}
public List<StorageUnit<? extends MyInterface>> getInstances() {
List<StorageUnit<? extends MyInterface>> instances = new ArrayList<StorageUnit<? extends MyInterface>>();
for (StorageUnit<? extends MyInterface> storageUnit : storageUnits) {
storageUnit.getInstances(/* I can't get the bound wildcard... */);
// Now loop through those instances and do something with them...
}
return instances;
}
}
That code sucks, so the best analogy I can think of is an actual storage unit container. That storage unit container has several individual storage units (think boxes). Each one of those boxes contains items of a certain type (think baseball cards). I know that a box contains 100 baseball cards, but until I open the box I don’t know anything about the details of each baseball card. I’m basically trying to treat each box as a lazy loader. Opening the box loads N implementations if they don’t exist already.
Paulo is correct, and (also as per Paulo’s answer), I often just pass a class object into a constructor to get around this problem. It allows the
getInstances()method to appear as you would like it – ie without parameters. Internally, the instance keeps a reference to the generic class so it can callnewInstance()on it.This code illustrates this using your example. I have tested this an it executes OK.