gpt4 book ai didi

Java 泛型 : Example if types are not erased at compilation

转载 作者:行者123 更新时间:2023-12-02 13:14:13 25 4
gpt4 key购买 nike

在 Java 中,泛型类型在编译时被删除,并用 Object 替代所有泛型参数,并完成隐式转换。这样做的原因是为了保持向后兼容性,如here所述。 。谁能给出一个 Java 1.5 之前的代码示例,如果 Java 1.5 在编译时没有删除类型,该示例会在运行时导致问题吗?

最佳答案

我认为您误解了类型删除的目的,首先 - 类型删除并不是为了避免运行时异常(而是为了避免任何运行时性能损失,更多信息即将到来...)以及其次 - 在 Java SE 5 之前,没有“泛型”,因此不存在“类型删除”的问题。

阅读here关于类型删除的目的:

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

因此,泛型中“类型删除”的主要目的之一是避免任何运行时性能损失,因为所有类型参数都会在编译时根据类型参数进行解析和验证,因此在运行时 JVM 需要浪费任何 CPU 周期。

请参阅下面的代码,它显示编译后类型已解析,并且由 JVM 解释的最终字节码不会留下任何类型参数。

编译前:

import java.util.Arrays;
import java.util.List;

public class TypeErasureExample {
public static void main(String[] args) {
List<String> stringList = Arrays.asList(new String[]{"a", "b", "c"});
List<?> numberList = Arrays.asList(new Integer[]{1, 2, 3});

System.out.println(stringList);
System.out.println(numberList);
}
}

编译后(反编译o/p):

import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;

public class TypeErasureExample
{
public static void main(String[] paramArrayOfString)
{
List localList1 = Arrays.asList(new String[] { "a", "b", "c" }); // Notice "List<String>" is converted to "List", this is what type erasure does.
List localList2 = Arrays.asList(new Integer[] { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3) }); // Notice "List<?>" is converted to "List", this is what type erasure does.

System.out.println(localList1);
System.out.println(localList2);
}
}

关于Java 泛型 : Example if types are not erased at compilation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43837769/

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