您的位置:首页 > 编程语言 > Java开发

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

2016-01-30 12:07 495 查看


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.

类型消除保证了没有为参数化类型而创建新的类;因此,泛型在运行时没有出现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 泛型