Java isAssignableFrom 理解

Java isAssignableFrom 理解

方法原型

 public native boolean isAssignableFrom(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:

  • JDK 1.1

参考译文

判定一个当前Class对象表示的类或者接口与传入的Class参数相比,是否相同,或者是否是它的一个超类或者超接口。是的话返回true,否则就返回false。当这个Class对象表示一种原始类型时,如果传入的Class对象参数就是这个Class对象,那么返回真,否则为假。

特别的,这个方法可以检查传入的Class参数所代表的类是否可以通过一个类型转换,或者一个扩大的引用转换转化为当前Class对象所表示的类型。更多细节请参考Java语言规范 5.1.1 和 5.1.4 两部分章节。

  • 参数: cls 需要检查的Class对象
  • 返回值:一个表示cls类的对象是否可以转换为这个类对象的布尔值
  • 抛出的异常:如果传入的cls参数为空,则抛出空指针异常
  • 版本:JDK 1.1

简明解析

先看段代码

import java.awt.List;
import java.util.ArrayList;
import java.util.Collection;

public class Main {

    public static void main(String[] args) {
        System.out.println(String.class.isAssignableFrom(Object.class));
        System.out.println(Object.class.isAssignableFrom(String.class));
        System.out.println(Object.class.isAssignableFrom(Object.class));
        System.out.println(List.class.isAssignableFrom(ArrayList.class));
        System.out.println(Iterable.class.isAssignableFrom(Collection.class));
    }
}

控制台输出:

false
true
true
false
true

可见,Object是String的超类,Object可以直接从String中得到赋值,即 Object is Assignable from String。因此第二个为真,第一个为假。第三条语句,两个类都是Object类,那么自然返回真。第四条语句中,ArrayList实现了List接口,两者的关系不是父子,故为假。最后一条语句中Collection接口扩展自Iterable类,即Iterable是Collection的超接口,故返回真。

综上所述,此方法可以用于判断两个Class或Interface间的父子关系。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值