Week 44 — What does "type erasure" refer to?
Question of the Week #44
What does "type erasure" refer to?
4 Replies
In Java, generics were implemented as a compile-time construct.
It is possible to use a generic type like the following:
The compiler is then able to check the type of the list and make sure only valid (with respect to the type) elements are inserted in the list as well as it allows obtaining items without (explicit) casting.
However, this information is not present at runtime. At runtime, an
ArrayList<String>
object is the same as an ArrayList<Object>
or an ArrayList<LocalDateTime>
or similar.
After compilation, the above code would be equivalent with the following:
Since no generic type information about objects is present at runtime, it is possible to insert call generic methods with invalid objects.
Raw types exist solely for compatibility and should not be used anywhere.
Instead, it is possible to use so-called wildcard types for generic types where the actual type parameter is unknown:
Aside from that, it is also not possible to extract the actual generic type parameters from a generic object since that information is not present at runtime.
For example, it is not generally possible to check whether an is a List<String>
, List<Object>
or a different List
. It is only possible to check whether or not it is a List
.
Unlike to objects, it is possible to get the generic type parameters of fields and methods using reflection:
📖 Sample answer from dan1st
Generics in java are actually totally fake, the runtime does not care about them. Type erasure refers to the java compiler resolving generic types to a common supertype, and making sure the runtime still works with those new types.
An example:
A generic type of <T> implicitly extends Object. Thus, using <T> like this:
compiles to:
(the cast in this case is unnecessary, but this would be about the use case)
Every generic type can be erased to a common supertype, with all the usages of the generic type enjoying type safety at compile time. At runtime, the uses are still entirely safe, because the java compiler has proven that the generic types being used are fully compatible. Using typed classes in a raw manner will defeat the java compiler's ability to do this tho, and should be used sparingly, if at all. That is a story for another time tho.
⭐ Submission from 0x150
Type erasure can be explained as the process of enforcing type constraints only at compile time and discarding the element type information at runtime.
Submission from shnehna