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

时间:2010-03-14 18:58:23

标签: java instanceof

如果实例完全属于给定类型,我需要测试。但是,如果子类型被测试为超类型,则似乎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)我该如何测试它们?

1 个答案:

答案 0 :(得分:17)

if( emailAttachment.getClass().equals(EmailAttachment.class) )