Why can't you create an instance of a generic type using “new” operator?

后端 未结 4 1840
萌比男神i
萌比男神i 2021-02-03 11:35

I found a lot of posts about how to overcome this limitation, but none about why this limitation exists (except this one, which just mentions it has to do with type era

4条回答
  •  渐次进展
    2021-02-03 11:55

    The shortest answer is that generic type parameters do not exist at runtime.

    Generics were retrofitted into the Java language in release 5. In order to maintain backward compatibility with the existing code base, they were implemented by erasure.

    Generic type parameters exist in your source code at compile-time, but nearly all evidence of them is removed in the byte code during compilation. This implementation of generics was chosen because it maintained inter-operability between pre-generics code and Java 5+ generic code. Type safety with generics is largely, therefore, a compile-time only phenomenon. If your generic code compiles without error and without warnings, then you are assured that your code is type safe.

    Because of erasure, however, there are (as of Java 5) two kinds of types:

    • Reifiable. For example String, Integer, etc. A reifiable type has the same type information at compile-time as it has at run-time.

    • Non-reifiable. For example List, List, and T. Non-reifiable types have less type information at run-time that at compile time. In fact, the run-time types of the above are List, List, and Object. During compilation, the generic type information is erased.

    You cannot use the new operator with non-reifiable types because there is no type safe way at run-time for the JVM to generate an object of the correct type.

    Source code:

    T myObject = new T();
    

    The above does not compile. At run-time, T has been erased.

    A strategy for circumventing some problems with type erasure and Java generics is to use type tokens. This strategy is implemented in the following generic method that creates a new T object:

    public  T newInstance(Class cls) {
        T myObject = cls.newInstance();
        return myObject;
    }
    

    The generic method captures the type information from the Class object that is passed as a parameter. This parameter is called a type token. Unfortunately, type tokens themselves must always be reifiable (because you can't get a Class object for a non-reifiable type) which can limit their usefulness.

提交回复
热议问题