Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method bounded type parameter and type erasure

Tags:

java

generics

A generic method as per below:

static <E, K extends E> void someMethod(K k, E[] e) {}

I presumed upon erasure, the erasure type would be:

static void someMethod(Object k, Object[] e) {}

Just curious how would the type parameter knows the constraints after type erasure? That type parameter K is bounded to E?

like image 797
yapkm01 Avatar asked Dec 16 '22 11:12

yapkm01


2 Answers

You are correct about the erasure. Actually, the runtime doesn't know about the constraints. Only the compiler does.

like image 120
Bohemian Avatar answered Jan 15 '23 06:01

Bohemian


Your type-erased signature is correct. However, the constraints of a method are not erased during compilation. They are encoded in metadata that is used at compile time (and not normally used at runtime although it can be accessed via reflection*). For example the class java.util.ArrayList<E> has the method:

public E get(int index)

Which with type-erasure becomes:

public Object get(int index)

However, in your code if you parameterize ArrayList with String then you will be to call the get(...) method without need to cast the result to a String despite the type-erasure.

This is different from what happens when you parameterize a class or method call. The provided parameterizations are completely erased at compile time. For example:

ArrayList<String> myList = new ArrayList<String>();

After compilation is equivalent to:

ArrayList myList = new ArrayList();

*Accessing this information at run time via reflection can be done by using reflection methods which return java.lang.reflect.Type instances. For example, to get the constraints of your method at runtime you could call java.lang.reflect.Method's getGenericParameterTypes() method. Processing this returned information would make it possible to determine the constraints at run time.

like image 39
Joshua Kaplan Avatar answered Jan 15 '23 08:01

Joshua Kaplan