Phoenix
Phoenix

Reputation: 8923

Java Generics type erasure casting

How does the java compiler know to provide appropriate cast to the objects in a generic collection when the type information isn't available at runtime due to erasure?

Upvotes: 2

Views: 1235

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198143

Whenever you call e.g. 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. The caller knows at compile time what the result should be cast to (a String), so the cast can be inserted there.

Upvotes: 2

kosa
kosa

Reputation: 66647

As per oracle tutorial

  • 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.

Upvotes: 0

Related Questions