Instantiating a generic type

suggest change

Due to type erasure the following will not work:

public <T> void genericMethod() {
    T t = new T(); // Can not instantiate the type T.
}

The type T is erased. Since, at runtime, the JVM does not know what T originally was, it does not know which constructor to call.


Workarounds

  1. Passing T’s class when calling genericMethod:
public <T> void genericMethod(Class<T> cls) {
    try {
        T t = cls.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
         System.err.println("Could not instantiate: " + cls.getName());
    }
}

<!-- -->
genericMethod(String.class);

Which throws exceptions, since there is no way to know if the passed class has an accessible default constructor.
  1. Passing a reference to T’s constructor:
public <T> void genericMethod(Supplier<T> cons) {
    T t = cons.get();
}
genericMethod(String::new);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Generics:
* Instantiating a generic type

Table Of Contents
6 Generics
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap