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

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

问题描述

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

解决方案

基本上,泛型在Java中的实现方式是通过编译器诡计。编译的泛型代码实际上只是使用 java.lang.Object 无论您谈论什么 T (或其他类型的参数) - 并且有一些元数据告诉编译器它确实是一个泛型类型。



当您针对泛型类型或方法编译某些代码时,编译器会计算出你的真正含义(即 T 的类型参数是什么),并在 compile 时验证你正在执行的操作正确的事情,但发出的代码再次就 java.lang.Object 来说话 - 编译器在必要时生成额外的强制转换。在执行时, List< String> List< Date> 完全相同;额外的类型信息已被编译器清除



比较这一点,比如说C#,其中信息在执行时保留,允许代码包含 typeof(T)等于 T.class 的表达式 - 除了后者是无效的。 (请注意,.NET泛型和Java泛型之间还存在其他差异。)类型擦除是处理Java泛型时出现的许多奇怪警告/错误消息的来源。



其他资源:


What is the concept of erasure in generics in Java?

解决方案

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.

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.

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.

Other resources:

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

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