Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no
(due to type erasure), but I'd be interested if anyone can see something I'm missing:
class SomeContainer<E>
{
E createContents()
{
return what???
}
}
EDIT: It turns out that Super Type Tokens could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.
I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's Artima Article.
You are correct. You can't do
new E()
. But you can change it toIt's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.
Dunno if this helps, but when you subclass (including anonymously) a generic type, the type information is available via reflection. e.g.,
So, when you subclass Foo, you get an instance of Bar e.g.,
But it's a lot of work, and only works for subclasses. Can be handy though.
You'll need some kind of abstract factory of one sort or another to pass the buck to:
Think about a more functional approach: instead of creating some E out of nothing (which is clearly a code smell), pass a function that knows how to create one, i.e.
If you need a new instance of a type argument inside a generic class then make your constructors demand its class...
Usage:
Pros:
Cons:
Foo<L>
proof. For starters...newInstance()
will throw a wobbler if the type argument class does not have a default constructor. This does apply to all known solutions though anyway.I thought I could do that, but quite disappointed: it doesn't work, but I think it still worths sharing.
Maybe someone can correct:
It produces:
Line 26 is the one with the
[*]
.The only viable solution is the one by @JustinRudd