Class.asSubclass signature

后端 未结 3 1197
有刺的猬
有刺的猬 2021-02-05 10:03

my question is quite theoretic... This is the signature of Class.asSubclass (Javadoc):

public  Class asSubclass(Class clazz)         


        
3条回答
  •  走了就别回头了
    2021-02-05 10:34

    The idea behind this method is exactly to add this wildcard. As far as I understand the purpose of this method is to cast this class object to a class object that represents any subclass of the parameter clazz. That is why the result is declared as Class (the class of something that extends U). Otherwise it wouldn't make sense, because its return type will be exactly the same as its only parameter's type, i.e. it will do nothing but return clazz;. It makes a runtime type check and casts the parameter to the Class (of course it will throw ClassCastException if the target of the invocation, i.e. this, does not represent the class of a U derivative). This is the better approach than simple (Class) type of casting, because the latter makes the compiler to produce a warning.

提交回复
热议问题