Skip to content

Instantly share code, notes, and snippets.

@shui
Last active November 14, 2017 11:33
Show Gist options
  • Save shui/0ce6c17a910b64e1c869c4fa3be6d689 to your computer and use it in GitHub Desktop.
Save shui/0ce6c17a910b64e1c869c4fa3be6d689 to your computer and use it in GitHub Desktop.
Java泛型擦除

在泛型代码内部,无法获得任何有关泛型参数类型的信息。

泛型类型只有在静态类型检查期间才会出现,在此之后,程序中所有的泛型类型都将被擦除,替换为他们的非泛型上界。例如,List<T>将被擦除为List,而普通的类型变量在未指定边界的情况下将被擦除为Object

擦除主要的正当理由是从非泛化代码到泛化代码的转变过程,以及在不破坏现有类库的情况下,将泛型融入Java语言。向后兼容性

擦除的代价是显著的。泛型不能用于显式地引用运行时类型的操作之中,例如转型、instanceof操作和new表达式,因为所有关于参数的类型信息都丢失了。

@shui
Copy link
Author

shui commented Nov 14, 2017

TIJ的翻译……

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment