Instance of type generic [duplicate]
The my question is this:
Why can not instantiate a generic type with new T () and instead with newInstance() of the class Class you can do?
You need to use reflection (newInstance()
), because at compile time the class whose constructor would need to be linked is unknown. So the compiler cannot generate the link.
Due to type erasure: the generic type doesn't know at execution time what T
is, so it can't call the right constructor.
See Angelika Langer's FAQ entry on type erasure for (much) more information.
Maybe, you're looking at this pattern (taken from an answer to another question):
private static class SomeContainer<E>
{
E createContents(Class<E> clazz)
{
return clazz.newInstance();
}
}
Here, when we create a SomeContainer
, we parametize the instance with a concrete class (like String
). createContents
will accept String.class
only and String.class.newInstance()
will create a new (empty) String.
If you know the type at compile time, use "new Whatever()". If you don't know the type at compile time but can get a Class object for it, use newInstance().
99% of the time I know the type and I use "new Whatever()".
精彩评论