Java Instance of: Supertypes und Subtypes seem to be equal? How to test exaclty for Type?

Posted by jens on Stack Overflow See other posts from Stack Overflow or by jens
Published on 2010-03-14T18:58:23Z Indexed on 2010/03/14 19:05 UTC
Read the original article Hit count: 355

Filed under:
|

Hello,

i would be thankful for your advice. I need to test, if an instance is exactly of a given type. But it seems that instanceof returns true also if the subtype is tested for the supertype (case 3). I never knew this before and I am quite surprised. Am I doing something wrong here? How do I exactly test for a given typen?

//..

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 only want "exact matches" (case 1 and 4) how to thest for them??

thanks!!! Jens

© Stack Overflow or respective owner

Related posts about java

Related posts about instanceof