Java instance: supertypes and subtypes seem equal? How to accurately test type?
•
Java
If an instance completely belongs to a given type, I need to test it However, if the subtype is tested as a supertype, it seems that instanceof also returns true (case 3) I've never known this before. I'm surprised Did I do wrong here? How do I accurately test a given type?
//.. 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"); }
result:
1 3 4
I want to avoid case 3. I just want "perfect match" (cases 1 and 4). How can I test them?
Solution
if( emailAttachment.getClass().equals(EmailAttachment.class) )
if( emailAttachment.getClass().equals(EmailAttachment.class) )
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码