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