Sobes.tech
Middle+

Is it possible to access the type of a generic during program execution?

sobes.tech AI

Answer from AI

No, it's not possible. Information about the generic type is erased during compilation (type erasure). Only "raw" types are available at runtime.

For example:

List<String> strings = new ArrayList<>();
// At runtime, this information will be lost:
// type erasure

Therefore, the following code will not work as expected:

if (list instanceof List<String>) { // Compilation error or warning
    // This code will not work as a check for List<String>
}

You can access information about the generic type through reflection, but only in certain cases, such as working with fields, methods, or class signatures where the type was explicitly specified in the source code.

Example of obtaining the collection type from a field:

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class MyClass {
    List<String> stringList;

    public static void main(String[] args) throws Exception {
        Field field = MyClass.class.getDeclaredField("stringList");
        Type genericType = field.getGenericType(); // Get Type containing information about <>

        if (genericType instanceof ParameterizedType) { // Check if the type is parameterized
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); // Get type arguments

            for (Type type : actualTypeArguments) {
                System.out.println("Element type: " + type.getTypeName()); // Will print "java.lang.String"
            }
        }
    }
}

But it is not possible to get the element type of a list created dynamically:

List<Integer> intList = new ArrayList<>();
// Here, information about Integer is lost at runtime

In the context of Android, this is especially important when working with libraries that use generics, such as Retrofit for parsing API responses. They often use constructs like TypeToken from Guava or similar to pass type information at runtime.

Example of using TypeToken (from Guava):

import com.google.common.reflect.TypeToken;
import java.util.List;

Type listStringType = new TypeToken<List<String>>() {}.getType();
// This Type object contains information about List<String> and can be used at runtime