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 }

 

转载于:https://www.cnblogs.com/halu126/p/6821209.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值