W3docs

Get generic type of class at runtime

If you want to get the generic type of a class at runtime, you can use the Type class in the System namespace.

If you want to get the generic type of a class at runtime in Java, you can use the java.lang.reflect.Type interface along with ParameterizedType. Due to type erasure, Java does not store generic type information directly in the class metadata, so you typically retrieve it from a superclass, interface, or field that declares the type parameter.

For example, if you have a class MyClass<T> that extends a generic base class, you can use the following code to get the type of T at runtime:


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

class Base<T> {}

public class MyClass<T> extends Base<T> {
    public static void main(String[] args) {
        Type type = MyClass.class.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] typeArgs = ((ParameterizedType) type).getActualTypeArguments();
            System.out.println(typeArgs[0]);
        }
    }
}

The getActualTypeArguments() method returns an array of Type objects representing the type arguments of the current generic type. In this case, there is only one type argument, so we can access it by indexing the array with 0.

Keep in mind that this relies on Java's reflection API. If the class does not extend a generic superclass or implement a generic interface that declares the type parameter, getGenericSuperclass() will return a raw Class object, and the instanceof ParameterizedType check will fail.

I hope this helps! Let me know if you have any other questions.