Here is the situation:
interface A{}//interface for entities
class B implements A{}//entity B
class C implements A{}//entity C
abstract class AR<E extends A>{}//generate list of E via a file,this will be done after the construct func.
class BR extends AR<B>{}
class CR extends AR<C>{}
Now I want to maintain:
Map<String,List<A>> data;//<filepath+filename, list of entities in file>
The func. blow will return the list based on the fileAddr:
<E extends A,R extends AR<E>> List<A> getList(String fileAddr)
{
if(data.containsKey(fileAddr))
return data.get(fileAddr);
else
{
AR<E> reader=new R(fileAddr);//generate a list of E via this file
List<E> values=reader.getValues();
data.put(fileAddr,values);
return values;
}
}
But this doesn’t work,and new R(fileAddr) is not supported.
So how to implement getList() func. based the spec. above.
You cannot use
newto generate an instance of a type parameter. The technical reason is that the type information has been erased by the time thatgetListis executed. Anyway, the Java language does not permit it.One way around the problem is to pass in a factory object that can create the required instance.
Another way around it is to pass the parameter type’s
Classobject as an argument, and then create the instance reflectively; e.g. something like this:(There will be a bunch of exceptions to deal with …)