Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Instance of: Supertypes and Subtypes seem to be equal? How to test exactly for Type?

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

like image 386
jens Avatar asked Mar 14 '10 18:03

jens


1 Answers

if( emailAttachment.getClass().equals(EmailAttachment.class) )
like image 179
marcosbeirigo Avatar answered Oct 19 '22 05:10

marcosbeirigo