为什么在 class 转换异常后无法检查实例类型?

Why can I not check instance type after class cast exception?

任何人都可以向我解释为什么以下代码块在 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
        }
    }
}

您的 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 没有检测到它是正确的