Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java type erasure vs. Field#getGenericType and Method#getGenericReturnType

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.

like image 854
Landon Kuhn Avatar asked May 28 '09 23:05

Landon Kuhn


People also ask

What are the two 2 types of Erasure?

- Erasure is a type of alteration in document. It can be classified as chemical erasure and physical erasure.

What is type erasure in Java?

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.

What is type erasure and when would you use it?

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 class converted to after type erasure?

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) { // ... }


1 Answers

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.

like image 72
cletus Avatar answered Sep 29 '22 11:09

cletus