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
  • 24

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
  • 50,165
  • 42
  • 145
  • 220
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,261,211
  • 792
  • 8,724
  • 8,929
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
  • 108,221
  • 16
  • 168
  • 253
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
  • 25,388
  • 9
  • 54
  • 105