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 can use:
But you need to supply the exact class name, including packages, eg.
java.io.FileInputStream
. I used this to create a math expressions parser.Java unfortunatly does not allow what you want to do. See http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects
You can do this now and it doesn't require a bunch of reflection code.
Of course if you need to call the constructor that will require some reflection, but that is very well documented, this trick isn't!
Here is the JavaDoc for TypeToken.
From Java Tutorial - Restrictions on Generics:
Cannot Create Instances of Type Parameters
You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:
As a workaround, you can create an object of a type parameter through reflection:
You can invoke the append method as follows:
Here is an option I came up with, it may help:
EDIT: Alternatively you can use this constructor (but it requires an instance of E):
An imporovement of @Noah's answer.
Reason for Change
a] Is safer if more then 1 generic type is used in case you changed the order.
b] A class generic type signature changes from time to time so that you will not be surprised by unexplained exceptions in the runtime.
Robust Code
Or use the one liner
One Line Code