3

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?

kafka
  • 949
  • 12
  • 27

4 Answers4

7

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.

Konrad Garus
  • 53,145
  • 43
  • 157
  • 230
7

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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.

Community
  • 1
  • 1
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

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()".

Jay
  • 26,876
  • 10
  • 61
  • 112