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)); } }
原文:http://www.cnblogs.com/greatfish/p/6097507.html