gpt4 book ai didi

java - 向上转换不会导致类型删除吗?

转载 作者:行者123 更新时间:2023-12-02 01:31:18 26 4
gpt4 key购买 nike

我最近遇到了在 instanceof 检查后将 object 向下转换为 String 的代码。

Object obj = this.get(key);
if(obj instanceof String) {
return (String) object;
}

我对它的工作原理有点困惑。我的理解是它不适用于泛型,因为类型删除使实例不引用原始类。此外,我的理解(由 this answer 证实)是,在运行时期间,向上转换为 Object 和使用泛型类型 T 之间没有区别。这是否意味着 instanceof 对于泛型无效的唯一原因是由于列出的编译时检查 here

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.

It is a compile-time error if the ReferenceType mentioned after the instanceof operator does not denote a reference type that is reifiable (§4.7).

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

尽管如此,答案还是像 this question 中的那样。似乎暗示运行时行为存在差异。对象通常确实在运行时包含类型信息,但在泛型的情况下会被删除吗?在向上转换的情况下,如何才能不删除该类型信息?

希望有人能够确定我的知识差距在哪里。我阅读了一些关于 instanceof here 的行为试图澄清,但这有点超出了我的范围,我希望得到更直接的答案。

最佳答案

对象总是知道它们真正是什么类型。

类型删除意味着泛型类型在编译的代码中“丢失”。例如。 List<String>被编译为原始 List ,逻辑上等价于List<Object>

但是,分配 String到声明为 Object 的变量不会导致类型删除,因为:

  1. 它不是泛型,因此类型删除不适用。

  2. 该对象知道它是 String ,无论变量的声明类型如何。
    这就是为什么你可以问它:

    • 你是一根绳子吗? x instanceof String

    • 你是什么? x.getClass()

关于java - 向上转换不会导致类型删除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56009870/

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