源码
/**
* 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);
翻译
Class a = A.class; Class b = B.class; boolean c = a.isAssignableFrom(b)
如果当前类对象(对应a)表示的类或者接口 是 参数类(对应b)表示的类或者接口 相同类型或者父类或者父接口。则返回true;否则返回false。当前类对象(对应a)表示的原始类型(原始类型一共有8种,它们分别是char,boolean,byte,short,int,long,float,double),如果参数类(对应b)和当前类对象(对应a)类型一样则返回true;否则返回false。
确切的说,这个方法用于判断参数类(对应b)表示的类型能否转换为当前类对象(对应a)表示的类型通过标识转换或者拓宽和窄化简单类型转换。详情请参阅 Java语言规范第5.1.1和5.1.4节。
实例
public class ChinaMadeCar extends ChinaMadeCarA implements DeviceA {
}
public class ChinaMadeCarA extends Test{
}
public class Test {
}
public interface DeviceA {
}
public class Chery extends ChinaMadeCar implements Car,Device{
public static void main(String[] args) {
//相同类 返回true
boolean b0 = Chery.class.isAssignableFrom(Chery.class);
//当前类对象直接父类ChinaMadeCar 返回true
boolean b1 = ChinaMadeCar.class.isAssignableFrom(Chery.class);
//当前类对象直接实现的接口Car 返回true
boolean b2 = Car.class.isAssignableFrom(Chery.class);
//当前类对象直接实现的接口Device 返回true
boolean b3 = Device.class.isAssignableFrom(Chery.class);
//父类ChinaMadeCar直接实现的接口DeviceA 返回true
boolean b4 = DeviceA.class.isAssignableFrom(Chery.class);
//间接父类ChinaMadeCarA(父类ChinaMadeCar的直接父类) 返回false
boolean b5 = ChinaMadeCarA.class.isAssignableFrom(Chery.class);
boolean b6 = Test.class.isAssignableFrom(Chery.class);
System.out.println("b0="+b0+"\n"+"b1="+b1+"\n"
+"b2="+b2+"\n"+"b3="+b3+"\n"+"b4="+b4+"\n"
+"b5="+b5+"\n"
+"b6="+b6);
}
}
// 控制台输出结果:
// b0=true
// b1=true
// b2=true
// b3=true
// b4=true
// b5=true
// b6=true
// b7=false