【问题标题】:Why can I not check instance type after class cast exception?为什么我不能在类转换异常后检查实例类型?
【发布时间】:2019-09-29 19:42:31
【问题描述】:

谁能向我解释为什么以下代码块在 Android Studio 中被突出显示为错误?

IDE 说 elem instanceof SubtypeB 总是错误的 - 这只是检查员的错误还是我需要了解的真实语言细节?。我可以安全地取消警告并保留当前代码吗?

示例代码:

for (Parcelable elem : list) {
    try {
        listOfSubtypeA.add( (SubtypeA) elem );
    } catch (ClassCastException cce) {
        //Line below is highlighted as always false
        if (elem instanceof SubtypeB) {
            ... //just logging
        }
    }
}

【问题讨论】:

  • SubtypeBParcelable有什么关系?
  • SubtypeA/B 在此处实现 Parcelable
  • 我无法重现该问题。您的释义版本是否有错误?你能提供一个包含所有相关代码的最小示例吗?
  • SubtypeASubtypeB是什么关系?
  • 请提供完整的程序,因为文字不是图片。

标签: android android-studio code-inspection


【解决方案1】:

您的 IDE 不正确。运行它:

 interface Test123  { }
static class SubtypeA implements Test123{ }
static class SubtypeB implements Test123 { }

public static void main(String[] args) {
    List<Test123> list = new ArrayList<>();
    list.add(new SubtypeB());
    List<SubtypeA> subList = new ArrayList<>();

    for (Test123 elem : list) {
        try {
            subList.add( (SubtypeA) elem );
        } catch (ClassCastException cce) {
            //Line below is highlighted as always false
            if (elem instanceof SubtypeB) {
                System.out.println("cce = " + cce);
        //just logging
            }
        }
    }
}

您将看到声明 if (elem instanceof SubtypeB) 被证明是正确的,因此您的 IDE 无法检测到它正确

【讨论】:

  • 这是我所期望的,我自己的代码也可以编译,我只是不想冒它在生产中崩溃的风险。出于好奇,我测试了您的代码,它也在我的 IDE 中突出显示。我想我只是要压制它,谢谢
  • 我明白了,也许你可以和你的同事讨论一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2021-02-14
  • 1970-01-01
  • 2018-11-04
  • 2011-11-20
  • 1970-01-01
相关资源
最近更新 更多