Java实例:超类型和子类型似乎相等?如何准确测试Type?

前端之家收集整理的这篇文章主要介绍了Java实例:超类型和子类型似乎相等?如何准确测试Type?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果一个实例完全属于给定类型,我需要测试.但是,如果子类型被测试为超类型,则似乎instanceof也返回true(情况3).我以前从来不知道这一点,我很惊讶.我在这里做错了吗?我如何准确测试给定类型?
//..

class DataSourceEmailAttachment extends EmailAttachment

//...

EmailAttachment emailAttachment = new EmailAttachment();
DataSourceEmailAttachment emailAttachmentDS = new DataSourceEmailAttachment();

    if (emailAttachment instanceof EmailAttachment){
        System.out.println(" 1");
    }
    if (emailAttachment instanceof DataSourceEmailAttachment){
        System.out.println(" 2");
    }

    if (emailAttachmentDS instanceof EmailAttachment){
        System.out.println(" 3 ");
    }
    if (emailAttachmentDS instanceof DataSourceEmailAttachment){
        System.out.println(" 4");
    }

结果:

1
 3 
 4

我想避免案例3,我只想要“完全匹配”(案例1和4)我该如何测试它们?

解决方法

if( emailAttachment.getClass().equals(EmailAttachment.class) )
原文链接:https://www.f2er.com/java/127074.html

猜你在找的Java相关文章