/**
* Determines if the class or interface represented by this
* {@code Class} object is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the specified
* {@code Class} parameter. It returns {@code true} if so;
* otherwise it returns {@code false}. If this {@code Class}
* object represents a primitive type, this method returns
* {@code true} if the specified {@code Class} parameter is
* exactly this {@code Class} object; otherwise it returns
* {@code false}.
*
* <p> Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* or via a widening reference conversion. See <em>The Java Language
* Specification</em>, sections 5.1.1 and 5.1.4 , for details.
*
* @param cls the {@code Class} object to be checked
* @return the {@code boolean} value indicating whether objects of the
* type {@code cls} can be assigned to objects of this class
* @exception NullPointerException if the specified Class parameter is
* null.
* @since JDK1.1
*/
public native boolean isAssignableFrom(Class<?> cls);
A isAssignableFrom B 是Class类的一个native方法,很多时候没直接用到,用Class对象的时候才会用到,A Class对象所代表的类或者接口 是否为B Class对象所代表的类或者接口,或者B Class对象所有代表的类或者接口的super类或者super接口,是的话就返回true否则false。
可以这样记忆,这2个方法代表的顺序刚好有点相反
听起来好拗口,确实,下面用代码例子来解释
class A {
}
class B extends A{
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, B.class.isAssignableFrom(A.class) + "");
Log.d(TAG, B.class.isAssignableFrom(B.class) + "");
Log.d(TAG, A.class.isAssignableFrom(A.class) + "");
Log.d(TAG, A.class.isAssignableFrom(B.class) + "");
Log.d(TAG, new A().getClass().isAssignableFrom(A.class) + "");
Log.d(TAG, new A().getClass().isAssignableFrom(B.class) + "");
Log.d(TAG, new B().getClass().isAssignableFrom(B.class) + "");
Log.d(TAG, new B().getClass().isAssignableFrom(A.class) + "");
}
因为我是直接在安卓项目里面测试的,所以有个onCreate(),改成纯java的对大家来说应该都不是事,忽略这个吧
看下打印结果
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: false
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: true
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: true
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: true
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: true
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: true
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: true
12-04 08:57:56.747 21395-21395/android.example.com.customannotationdemo D/MainActivity: false
相信不用我解释,看到这个结果大家应该都明白了