samedi 19 octobre 2019

Generic type information is known at runtime by ParameterizedType [duplicate]

In the following example, generic type information is available at runtime through the ParameterizedType class.

import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;

class Generic<T> {};

class NonGeneric extends Generic<Integer> {};

class Main {
    public static void main(String[] args) {
        ParameterizedType parameterizedType =
            (ParameterizedType)
            new NonGeneric().getClass().getGenericSuperclass();

        for (Type typeArg : parameterizedType.getActualTypeArguments()) {
            System.out.println(typeArg);
        }
    }
}

Output:

class java.lang.Integer

How is this possible given the nature of type erasure? I would have expected this information to be unavailable.





Aucun commentaire:

Enregistrer un commentaire