Java泛型中擦除的概念是什么? [英] What is the concept of erasure in generics in Java?

查看:25
本文介绍了Java泛型中擦除的概念是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 泛型中擦除的概念是什么?

What is the concept of erasure in generics in Java?

推荐答案

这基本上是通过编译器技巧在 Java 中实现泛型的方式.编译后的泛型代码实际上只使用 java.lang.Object 无论你在哪里谈论 T(或其他一些类型参数) - 还有一些元数据告诉编译器它确实是一个泛型类型.

It's basically the way that generics are implemented in Java via compiler trickery. The compiled generic code actually just uses java.lang.Object wherever you talk about T (or some other type parameter) - and there's some metadata to tell the compiler that it really is a generic type.

当您针对泛型类型或方法编译某些代码时,编译器会计算出您真正的意思(即 T 的类型参数是什么)并在 compile 时间你做正确的事情,但发出的代码再次只是根据 java.lang.Object 说话 - 编译器在必要时生成额外的强制转换.在执行时,一个List和一个List是完全一样的;额外的类型信息已被编译器擦除.

When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for T is) and verifies at compile time that you're doing the right thing, but the emitted code again just talks in terms of java.lang.Object - the compiler generates extra casts where necessary. At execution time, a List<String> and a List<Date> are exactly the same; the extra type information has been erased by the compiler.

将其与 C# 进行比较,其中信息在执行时保留,允许代码包含诸如 typeof(T) 之类的表达式,它等效于 T.class - 除了后者无效.(请注意,.NET 泛型和 Java 泛型之间还有进一步的区别.)在处理 Java 泛型时,类型擦除是许多奇怪"警告/错误消息的来源.

Compare this with, say, C#, where the information is retained at execution time, allowing code to contain expressions such as typeof(T) which is the equivalent to T.class - except that the latter is invalid. (There are further differences between .NET generics and Java generics, mind you.) Type erasure is the source of many of the "odd" warning/error messages when dealing with Java generics.

其他资源:

  • Oracle documentation
  • Wikipedia
  • Gilad Bracha's Java generics guide (PDF - highly recommended; link may need to change periodically)
  • Angelika Langer's Java Generics FAQ

这篇关于Java泛型中擦除的概念是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆