美文网首页
Java 对象与类,对象与接口,类与接口之间的关系判断。

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

作者: 不敢预言的预言家 | 来源:发表于2018-02-07 14:02 被阅读0次

(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

相关文章

网友评论

      本文标题:Java 对象与类,对象与接口,类与接口之间的关系判断。

      本文链接:https://www.haomeiwen.com/subject/nynozxtx.html