Java 对象与类,对象与接口,类与接口之间的关系判断。

(new yy()) instanceof xx.class 判断 yy对象 否是 xx类 的实例
xx.class.isAssignableFrom(yy.class) 判断 yy类 是否为 xx类 的子类或实现

/**
 * 两个Class判断
 */
// 判断对象是否为实例
ChildClass child = new ChildClass();
System.out.printf("child对象 是不是 ChildClass 的实例 %s\n", 
        child instanceof ChildClass); 
            // true

System.out.printf("child对象 是不是 FatherClass 的实例 %s\n", 
        child instanceof FatherClass); 
            // true

// 判断类是否继承某类
System.out.printf("FatherClass 是不是 ChildClass 的父类 %s\n", 
        FatherClass.class.isAssignableFrom(ChildClass.class)); 
            // true


/**
 * 接口和实现类判断
 */
// 判断对象是否为实例
AbstractInterfaceImpl impl = new AbstractInterfaceImpl();
System.out.printf("impl对象 是不是 AbstractInterfaceImpl 的实例 %s\n", 
        impl instanceof AbstractInterfaceImpl); 
            // true

System.out.printf("impl对象 是不是 AbstractInterface 的实例 %s\n", 
        impl instanceof AbstractInterface); 
            // true

// 判断类是否为接口实现
System.out.printf("AbstractInterfaceImpl 是不是 AbstractInterface 的接口实现 %s\n", 
        AbstractInterface.class.isAssignableFrom(AbstractInterfaceImpl.class)); 
            // true

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容