class1.isAssignableFrom(class2) 判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同,或是否是其超类或超接口。如果是则返回 true;否则返回 false。如果该 Class 表示一个基本类型,且指定的 Class 参数正是该 Class 对象,则该方法返回 true;否则返回 false。
1. class2是不是class1的子类或者子接口
2. Object是所有类的父类
一个例子搞定:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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的用法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。