Generic class raw instance lose all generic ability

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kang389110772/article/details/89467331

Generic class raw instance lose all generic ability

在使用一个泛型的class的时候,如果不用类型去实例化,那么就会丢掉所有的泛型推断能力。

参考下面SO的回复。

It’s not exactly what you’d expect, but if you refer to a generic class in raw form, you lose the ability to use generics in any way for instance members. It’s not restricted to generic methods either, check out this:

 public class MyContainer<T> {

     public List<String> strings() {
         return Arrays.asList("a", "b");
     }
 }

MyContainer<Integer> container = new MyContainer<>(1);
List<String> strings = container.strings();
MyContainer container2 = new MyContainer<>(2);
List<String> strings2 = container2.strings(); // unchecked warning

This is the relevant part of the JLS (4.8):

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

猜你喜欢

转载自blog.csdn.net/kang389110772/article/details/89467331
今日推荐