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
.javafile, Java produces a single.classfile for that class.No, nothing is replaced in the method. Once the
.classfile is generated, that's what you get. When compiling, the compiler simply verifies that theStringtype is an acceptable type argument for theappend()method. Since you've specified no bounds onE, the compiler judges thatStringis 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
Eis.There are a few alternatives for getting an instance of whatever type
Tends up being. See here: