I know Java does not allow not Create Instances of Type Parameters. Many articles simply said "Type Erase" as the reason. But does type parameters initialization not occur before type erase? Is Type Erase the only reason? Here is a example:
public class GenObj {
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
public static main(){
List<String> list= new ArrayList<String>();
GenOjb.append<String>(list);
}
}
When we call the generic method using GenOjb.append(list), I think the compiler will replace E in the method with String first and then do "Type Erase", is that correct? If so, as long as we have a way to ensure E does indeed have a default constructor, we should be able to create instance of type parameters. Can someone explain in more detail why Java does not allow creating instance of parameter type? Thanks.
Remember that Generics are for compile time checking and that when you compile a class within
.java
file, Java produces a single.class
file for that class.No, nothing is replaced in the method. Once the
.class
file is generated, that's what you get. When compiling, the compiler simply verifies that theString
type is an acceptable type argument for theappend()
method. Since you've specified no bounds onE
, the compiler judges thatString
is an acceptable type argument.That's just not how the java language works. Class instantiation happens at run time. At run time, there is no longer any notion of type variables because of type erasure and therefore we cannot know what
E
is.There are a few alternatives for getting an instance of whatever type
T
ends up being. See here: