The Java™ Tutorials — Generics :Type Erasure 类型消除

The Java™ Tutorials — Generics :Type Erasure 类型消除

原文地址:https://docs.oracle.com/javase/tutorial/java/generics/erasure.html

关键点

  • 功能:保证了泛型不在运行时出现
  • 类型消除应用的场合: 
    • 编译器会把泛型类型中所有的类型参数替换为它们的上(下)限,如果没有对类型参数做出限制,那么就替换为Object类型。因此,编译出的字节码仅仅包含了常规类,接口和方法。
    • 在必要时插入类型转换以保持类型安全。
    • 生成桥方法以在扩展泛型时保持多态性。

全文翻译

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.

泛型被引入到Java语言的目的是提供更加严格的编译时类型检查,以及提供对泛型编程的支持。为了实现泛型,Java编译器将类型消除应用到了如下场合:

  • 编译器会把泛型类型中所有的类型参数替换为它们的上(下)限,如果没有对类型参数做出限制,那么就替换为Object类型。因此,编译出的字节码仅仅包含了常规类,接口和方法。
  • 在必要时插入类型转换以保持类型安全。
  • 生成桥方法以在扩展泛型时保持多态性。

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

类型消除保证了没有为参数化类型而创建新的类;因此,泛型在运行时没有出现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值