Suppose I have the following method, which can be used to create a collection of a given type specified.
private static Collection<?> void create(Class<? extends Collection<?>> cls) {
return cls.newInstance();
}
This is all good if the cls argument is passed in during runtime:
List<String> list = new LinkedList<String>();
create(list.getClass());
But how do I invoke this method in code without an unchecked warning? Say I want to do something like:
create(LinkedList.class);
It’ll complain that create(Class) is not defined, which strictly speaking is correct because List is not #capture of Collection, but how do I make it work?
Many thanks!
Neal Gafter talks about pretty much exactly this problem here. The fix is to use super type tokens. This is what Guice uses to maintain generic type information, I believe.
Basically it’s an extra class you can use to represent a type instead of using
Foo.class. You’d use it like this:Note that your attempt to use the raw type
LinkedListwould still cause the compiler to complain, and deliberately so – when you use raw types, you’re basically opting out of type safety. But this scheme allows you to express the generic type in a way which is otherwise harder.