Why can't assign I <? extends Type> to ?

后端 未结 2 1126
半阙折子戏
半阙折子戏 2020-12-11 18:22

The following statements:

URLClassLoader ucl = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class uclc = ucl.getClass();
         


        
2条回答
  •  醉酒成梦
    2020-12-11 18:39

    Why can't assign I to ?

    Because actually is a supertype of ! Let's follow the specification.

    4.10.2 Subtyping among Class and Interface Types:

    Given a generic type declaration C1,...,Fn>, the direct supertypes of the parameterized type C1,...,Tn> are all of the following:

    • C1,...,Sn>, where Si contains Ti.

    4.5.1. Type Arguments of Parameterized Types:

    A type argument T1 is said to contain another type argument T2, written T2 <= T1, if the set of types denoted by T2 is provably a subset of the set of types denoted by T1 under the reflexive and transitive closure of the following rules:

    • T <= ? extends T

    We therefore know that since ? extends URLClassLoader contains URLClassLoader, Class is a supertype of Class.

    Because a narrowing reference conversion is not permitted within an assignment context, a compilation error occurs.

    Also note that this means the reverse assignment is permitted:

    Class concrete = URLClassLoader.class;
    Class wildcard = concrete;
    

提交回复
热议问题