vendredi 25 mars 2022

Get Class-object representation of generic parameter in Java

I am trying to retrieve the Class<?> representation of a type parameter at runtime like this:

public <E extends Exception> Try<T> onCatch (Consumer<E> onCatch) { 
    // retrieve `Class<E>`
}

While normally it is not possible to retrieve the types at runtime because of type erasure, due to reflection utilities and meta-data stored about generics in bytecode it should be possible like seen in this answer to the same question I have.

The accepted answer looks the following

Class<T> persistentClass = (Class<T>)
   ((ParameterizedType)getClass().getGenericSuperclass())
      .getActualTypeArguments()[0];

but does not work for me, due to .getActualTypeArguments()[0] not being an instance of ParameterizedType but Class and thus failing the cast.

Is there any way to reliably do this? I know I can manually pass a Class<E> reference to the method but due to this being a library being able to just use the generic type would be much more convenient.





Aucun commentaire:

Enregistrer un commentaire