gpt4 book ai didi

: Supertypes and Subtypes seem to be equal?的Java实例如何准确测试类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:45:15 26 4
gpt4 key购买 nike

我需要测试一个实例是否完全属于给定类型。但是,如果针对父类(super class)型测试子类型(情况 3),instanceof 似乎也会返回 true。我以前从来不知道这一点,我很惊讶。我在这里做错了什么吗?如何准确测试给定类型?

//..

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) )

关于: Supertypes and Subtypes seem to be equal?的Java实例如何准确测试类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2443326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com