Generics, factories and reflection

M

Martin

Hi.

I have a problem with a factory method. This method should create
instances of the collection framework. The simplest implementation
looks like this:

--------------------------------------------------------------
public static List<E> createList() {
return new ArrayList<E>();
}
List<String> l1 = createList();
--------------------------------------------------------------

But in my special case, I want to (and have to) pass the implementing
class as an argument. So the factory could create instances of
ArrayList but also of LinkedList. The following method compiles without
warnings and errors:

--------------------------------------------------------------
public static List<E> createList(Class<? extends List<E>> listImpl) {
try {
List<E> l = listImpl.newInstance();
return l;
}
catch (Exception dontBotherMe) {
return null;
}
}
--------------------------------------------------------------

But how can I call this method?

List<String> l2 = createList(ArrayList.class)

does not work, because "Class<ArrayList>" does not match
"Class<List<E>>".
 
T

Thomas Hawtin

Martin said:
> public static List<E> createList() {
public static <E> List<E> createList() {

You need to declare the generic parameter.
But in my special case, I want to (and have to) pass the implementing
class as an argument. So the factory could create instances of
ArrayList but also of LinkedList. The following method compiles without
warnings and errors:

--------------------------------------------------------------
public static List<E> createList(Class<? extends List<E>> listImpl) {
try {
List<E> l = listImpl.newInstance();
return l;

I strongly suggest you don't use Class.newInstance. That method is evil.
Much better to write an abstract factory interface. Also, important for
this use, Class represents an erased type. In any case, creating a
LinkedList is likely to be a bad idea.
}
catch (Exception dontBotherMe) {
return null;
}
}

Nice error handling...

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,121
Latest member
LowellMcGu
Top