標籤:blog assign stat ima isa 技術 static test .class
class1.isAssignableFrom(class2) 判定此 Class
對象所表示的類或介面與指定的 Class
參數所表示的類或介面是否相同,或是否是其超類或超介面。如果是則返回 true
;否則返回 false
。如果該 Class
表示一個基本類型,且指定的 Class
參數正是該 Class
對象,則該方法返回 true
;否則返回 false
。
1.class2是不是class1的子類或者子介面
2.Object是所有類的父類
一個例子搞定:
package com.auuzee.test1;class A {}class B extends A {}public class Test1 { public static void main(String[] args) { A a = new A(); B b = new B(); A ba = new B(); System.out.println("1-------------"); System.out.println(A.class.isAssignableFrom(a.getClass())); System.out.println(B.class.isAssignableFrom(b.getClass())); System.out.println(A.class.isAssignableFrom(b.getClass())); System.out.println(B.class.isAssignableFrom(a.getClass())); System.out.println(A.class.isAssignableFrom(ba.getClass())); System.out.println(B.class.isAssignableFrom(ba.getClass())); System.out.println("2-------------"); System.out.println(a.getClass().isAssignableFrom(A.class)); System.out.println(b.getClass().isAssignableFrom(B.class)); System.out.println(a.getClass().isAssignableFrom(B.class)); System.out.println(b.getClass().isAssignableFrom(A.class)); System.out.println(ba.getClass().isAssignableFrom(A.class)); System.out.println(ba.getClass().isAssignableFrom(B.class)); 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)); System.out.println("abc".getClass().isAssignableFrom(Object.class)); }}
Java中isAssignableFrom的用法