As I understand them, generics are a compile time feature of Java, and parametrized type information does not exist in the compiled byte code. I have now discovered the Field#getGenericType and Method#getGenericReturnType methods, thusly shattering my world view. Please help me to piece it together.
- Erasure is a type of alteration in document. It can be classified as chemical erasure and physical erasure.
Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.
Type-erasure simply means "erasing" a specific type to a more abstract type in order to do something with the abstract type (like having an array of that abstract type).
What is the following method converted to after type erasure? public static <T extends Comparable<T>> int findFirstGreaterThan(T[] at, T elem) { // ... } Answer: public static int findFirstGreaterThan(Comparable[] at, Comparable elem) { // ... }
When you're dealing with a jar of compiled bytecode in your IDE, you can still get generic auto-completion. This is how it's implemented. Basically you're right: types aren't completely erased.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With