My tests show that Java reflection cannot determine object types assigned at runtime to a generic object reference that uses a wildcard declaration. To overcome that problem, I wrote the following. How can this be improved? For starters, I get a raw type complaint when I declare a Class object but how else is this not a best practice example for determining the runtime type assigned to a wildcard reference?
class TestRuntimeType
{
public static void main(String... args) throws Exception
{
Map<Integer, Inventory<?>> map = new HashMap<Integer, Inventory<?>>();
Inventory<Shirt> janesShirts = new Inventory<Shirt>(new Shirt());
janesShirts.add(new Shirt("jack", 17));
map.put(0, janesShirts);
CConsole.myPW.format("%s\n", map.get(0).getElementType());
}
}
class Inventory<T> extends ArrayList<T>
{
private Class elementType;
Inventory(T example)
{
elementType = example.getClass();
}
Class getElementType()
{
return elementType;
}
}
class Shirt
{ String maker; double size;
Shirt() {}
Shirt(String maker, double size)
{ this.maker = maker; this.size = size; }
}
The best way to specify a class is to use that class. To avoid having to give the class twice you can use a factory.