首页 > 代码库 > Class对象的isAssignableFrom方法

Class对象的isAssignableFrom方法

isAssignableFrom

在看一个开源代码时,在加载完某个Class对象后,经常会使用 java.lang.Class#isAssignableFrom 来校验下。

之前真没有注意过Class对象中还有个这样的方法,下面是是这个方法的定义:

public native boolean isAssignableFrom(Class<?> cls);

他到底是干什么用的呢?

先来看下Java源码中的注释:

java.lang.Class
public boolean isAssignableFrom(@org.jetbrains.annotations.NotNull Class<?> cls)
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.
Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.
Parameters:
cls - the Class object to be checked
Returns:
the boolean value indicating whether objects of the type cls can be assigned to objects of this class
Throws:
NullPointerException - if the specified Class parameter is null.
Since:
JDK1.1

哦。。。

就是判断下该Class对象所描述的class和interface和参数cls所描述的class和interface是不是同样的,或者是参数cls所描述的class和interface的超类/超接口。

instanceof

立马让我联想到Java的关键字: instanceof 

instanceof的作用是判断对象是不是指定的类型或子类型。

isInstance

如果你稍微认真点,还会发现Class对象中还有个关于对象继承关系的方法:

public native boolean isInstance(Object obj);

对应的注释:

This method is the dynamic equivalent of the Java language instanceof operator.

等价于关键字 instanceof 

使用样例

虽然这里既有对象,又有Class对象,但是他们所判断的都是,对象与Class对象所描述的class/interface的关系,而不是与Class对象关系

 1 public class TestInstance extends Test {
 2 
 3     public static void main(String[] args) {
 4 //        Object test = new Object();
 5 //        TestInstance test = new TestInstance();
 6         Test test = new Test();
 7         System.out.println(test instanceof Test);                   //true
 8         System.out.println(test instanceof TestInstance);              //false
 9 
10         System.out.println(Test.class.isAssignableFrom(TestInstance.class));  //true
11         System.out.println(TestInstance.class.isAssignableFrom(Test.class));  //false
12         System.out.println(Test.class.isInstance(test));              //true
13         System.out.println(TestInstance.class.isInstance(test));         //false
14     }
15 }

 

Class对象的isAssignableFrom方法