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.
When you are working with E at compile time you don't really care the actual generic type "E" (either you use reflection or work with base class of generic type) so let the subclass provide instance of E.
There are various libraries that can resolve
E
for you using techniques similar to what the Robertson article discussed. Here's an implemenation ofcreateContents
that uses TypeTools to resolve the raw class represented by E:This assumes that getClass() resolves to a subclass of SomeContainer and will fail otherwise since the actual parameterized value of E will have been erased at runtime if it's not captured in a subclass.
If you want not to type class name twice during instantiation like in:
You can use factory method:
Like in:
You can achieve this with the following snippet:
Here's an implementation of
createContents
that uses TypeTools to resolve the raw class represented byE
:This approach only works if
SomeContainer
is subclassed so the actual value ofE
is captured in a type definition:Otherwise the value of E is erased at runtime and is not recoverable.