What's the logic behind the limitaion of doing the following in Java?
public class genericClass<T>{
void foo(){
T t = new T(); //Not allowed
}
}
Because of type erasure.
The runtime does not know the "real" type of T, it is Object for it. You code would be more or less read like this:
public class genericClass {
void foo(){
Object t = new Object(); //Not allowed
}
}
If you need to do such a thing, you need to use reflection:
public class GenericClass<T> {
private final Class<? extends T> clazz;
public GenericClass(Class<? extends T> clazz) {
this.clazz = clazz;
}
void foo() {
T t = clazz.newInstance();
}
}
In Java, generics is implemented using type erasure which means generic type information is erased at compile time. This means that the information for constructing the object isn't available at runtime.
().foo()` do?)
– user253751 Jul 19 '14 at 12:20