isAssignableFrom 是用来判断一个类Class1和另一个类Class2是否相同或是另一个类的超类或接口。
通常调用格式是
Class1.isAssignableFrom (Class2)
调用者和参数都是 java.lang.Class 类型。
简单例子
public class A {
}
public class B extends A {
}
测试
/**Class.isAssignableFrom
* isAssignableFrom 是用来判断一个类Class1和另一个类Class2是否相同或是另一个类的超类或接口。
* @author 刘楠
*
*/
public class Test2 {
public static void main(String[] args) {
A a = new A();
B b = new B();
A ba = new B();
System.out.println(a.getClass());
System.out.println(b.getClass());
System.out.println(ba.getClass());
System.out.println("=====================");
System.out.println(a.getClass().isAssignableFrom(b.getClass()));//true
System.out.println(b.getClass().isAssignableFrom(a.getClass()));//false
System.out.println("=====================");
System.out.println(ba.getClass().isAssignableFrom(a.getClass()));//false
System.out.println(a.getClass().isAssignableFrom(ba.getClass()));//true
System.out.println("=====================");
System.out.println(ba.getClass().isAssignableFrom(b.getClass()));//true
System.out.println(b.getClass().isAssignableFrom(ba.getClass()));//true
System.out.println("1-------------");
System.out.println(A.class.isAssignableFrom(a.getClass()));//true
System.out.println(B.class.isAssignableFrom(b.getClass()));//true
System.out.println(A.class.isAssignableFrom(b.getClass()));//true
System.out.println(B.class.isAssignableFrom(a.getClass()));//false
System.out.println(A.class.isAssignableFrom(ba.getClass()));//true
System.out.println(B.class.isAssignableFrom(ba.getClass()));//true
System.out.println("2-------------");
System.out.println(a.getClass().isAssignableFrom(A.class));//true
System.out.println(b.getClass().isAssignableFrom(B.class));//true
System.out.println(a.getClass().isAssignableFrom(B.class));//true
System.out.println(b.getClass().isAssignableFrom(A.class));//false
System.out.println(ba.getClass().isAssignableFrom(A.class));//false
System.out.println(ba.getClass().isAssignableFrom(B.class));//true
System.out.println("3-------------");
System.out.println(Object.class.isAssignableFrom(b.getClass()));
System.out.println(Object.class.isAssignableFrom("abc".getClass()));
System.out.println("4-------------");
System.out.println("a".getClass().isAssignableFrom(Object.class));//string false
System.out.println("abc".getClass().isAssignableFrom(Object.class));//string false
}
结果
class com.ghgcn.test01.A
class com.ghgcn.test01.B
class com.ghgcn.test01.B
=====================
true
false
=====================
false
true
=====================
true
true
1-------------
true
true
true
false
true
true
2-------------
true
true
true
false
false
true
3-------------
true
true
4-------------
false
false