简体   繁体   English

Java泛型擦除类型转换

[英]Java Generics type erasure casting

当类型信息由于擦除而在运行时不可用时,java编译器如何知道为通用集合中的对象提供适当的转换?

Whenever you call eg list.get(foo) , and the list is an ArrayList<String> , then the result of get is casted to a String by the caller , not the callee. 每当您调用例如list.get(foo)且列表是ArrayList<String>get的结果get调用者 (而不是被调用 list.get(foo)转换为String The caller knows at compile time what the result should be cast to (a String ), so the cast can be inserted there. 调用者在编译时就知道应该将结果强制转换为( String ),因此可以在其中插入强制转换。

As per oracle tutorial 根据Oracle 教程

  • 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. 生成桥接方法以在扩展的泛型类型中保留多态。

So, your class file contains either bounded class (or) Object instead of generic type. 因此,您的类文件包含有界的类(或)对象,而不是泛型类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM