Reputation: 50087
Within my method readList
, I would like to build a java.util.List
of a user-defined type (the concrete list type is a parameter). I don't want to restrict readList
to ArrayList
or LinkedList
however; the user might supply his own java.util.List
implementation. The method might also cache the list if possible, so the method needs to return the list. I tried a few things. Which one of the following is the 'best' API in your view, or is there another, even better one?
The following compiles, but I get the compiler warning: "Type safety: The expression of type ArrayList needs unchecked conversion to conform to ArrayList", so it's not really a good solution:
void classParameter() {
ArrayList<String> a = readList(ArrayList.class);
LinkedList<String> b = readList(LinkedList.class);
}
<X, T extends List<X>> T readList(Class<T> clazz) {
try {
return clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
The following compiles, but I still get the compiler warning, plus it doesn't actually work as expected:
void classTypeParameters() {
ArrayList<String> a = readList(ArrayList.class, String.class);
LinkedList<String> b = readList(LinkedList.class, Integer.class);
}
<T extends List<X>, X> T readList(Class<T> clazz, Class<X> type) {
try {
return clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
The following works, and is my personal favorite. It checks the list type. What is a bit dangerous is somebody could by mistake forget to assign the result. This could be solved by renaming readList
to readListWithTemplate
or so, it would be more obvious the return value is to be used. It's similar to List.toArray(T[] a)
:
void template() {
ArrayList<String> a = readList(new ArrayList<String>());
LinkedList<String> b = readList(new LinkedList<String>());
// wrong usage:
List<String> c = new LinkedList<String>();
readList(c);
}
@SuppressWarnings("unchecked")
<X, T extends List<X>> T readList(T template) {
try {
return (T) template.getClass().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
The "super token type" works as well, but might be bit hard to understand for developers not familiar with this pattern, and in Eclipse I get the warning "Empty block should be documented", which I would like to avoid:
void superTypeToken() {
ArrayList<String> a = readList(new ListType<ArrayList<String>>() {});
LinkedList<String> b = readList(new ListType<LinkedList<String>>() {});
}
abstract static class ListType<X extends List<?>> {
// super type token class
}
@SuppressWarnings("unchecked")
<X, T extends List<X>> T readList(ListType<T> t) {
try {
Type type = t.getClass().getGenericSuperclass();
if (!(type instanceof ParameterizedType)) {
throw new IllegalArgumentException("Missing type parameters");
}
ParameterizedType pt = (ParameterizedType) type;
type = pt.getActualTypeArguments()[0];
pt = (ParameterizedType) type;
Class<?> listClass = (Class<?>) pt.getRawType();
return (T) listClass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Which one do you prefer? Or is there a better solution?
Upvotes: 4
Views: 551
Reputation: 40703
I would probably delegate to another builder class. A small class that just knows how to create new lists. It provides better runtime safety as it does not rely on the assumption that the given class has a default constructor. Maybe not so useful with lists as we should always be able to create an empty list, but more important with other types of class.
eg.
public interface EmptyListBuilder {
public <E> List<E> newList();
public static final EmptyListBuilder ARRAY_LIST_BUILDER =
new EmptyListBuilder() {
public <E> List<E> newList() {
return new ArrayList<E>();
}
};
}
As shown by the static field you can also provide a default implementation for a few standard classes.
Use the class like this:
<T> List<T> readList(EmptyListBuilder builder) {
List<T> list = builder.newList();
// read in elements
return list;
}
You lose being able to know exactly what type of list you have, but of that's an issue then it sounds like you're trying to do something a little odd.
Upvotes: 4