Class類的isAssignableFrom是個不常用的方法导犹,感覺這個方法的名字取得不是很好,所以有必要在此解析一下春缕,以免在看源碼時產生歧義挎塌,這個方法的簽名如下:
<pre style="margin: 0px; padding: 0px; overflow: auto; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">public native boolean isAssignableFrom(Class<?> cls);</pre>
由方法簽名可見是一個本地方法,即C代碼編寫的车酣。
以下是JDK中的注釋:
Determines if the class or interface represented by this Class
object is either the same as,
or is a superclass or superinterface of, the class or interface represented by the specified Class
parameter.
It returns true
if so; otherwise it returns false
.
If this Class
object represents a primitive type, this method returns true
if the specified Class
parameter is exactly this Class
object; otherwise it returns false
.
意思如下:
有兩個Class類型的類象曲稼,一個是調用isAssignableFrom方法的類對象(后稱對象a)索绪,以及方法中作為參數的這個類對象(稱之為對象b),這兩個對象如果滿足以下條件則返回true躯肌,否則返回false:
a對象所對應類信息是b對象所對應的類信息的父類或者是父接口者春,簡單理解即a是b的父類或接口
a對象所對應類信息與b對象所對應的類信息相同破衔,簡單理解即a和b為同一個類或同一個接口
測試代碼:
//說明:Protocol是接口清女,DubboProtocol是Protocol的實現(xiàn)
protocolClass.isAssignableFrom(dubboProtocolClass )) ; //返回true
protocolClass.isAssignableFrom(protocolClass )) ; //返回true
dubboProtocolClass.isAssignableFrom(protocolClass )) ; //返回false</pre>