2

Is there a way in Java to reflect a generic type of a local variable? I know you can do that with a field - Get generic type of java.util.List. Any idea how to solve, for instance:

public void foo(List<String> s){
  //reflect s somehow to get String
}

Or even more general:

public void foo<T>(List<T> s){
  //reflect s somehow to get T
}
Mikhail2048
  • 1,715
  • 1
  • 9
  • 26
Bober02
  • 15,034
  • 31
  • 92
  • 178

2 Answers2

7

No. Due to Java's Type Erasure, all generics are stripped during the compile process.

You can however use instanceOf or getClass on elements in the list to see if they match a specific type.

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
1

Here is nice tutorial that shows how and when you can read generic types using reflection. For example to get String from your firs foo method

public void foo(List<String> s) {
    // ..
}

you can use this code

class MyClass {

    public static void foo(List<String> s) {
        // ..
    }

    public static void main(String[] args) throws Exception {
        Method method = MyClass.class.getMethod("foo", List.class);

        Type[] genericParameterTypes = method.getGenericParameterTypes();

        for (Type genericParameterType : genericParameterTypes) {
            if (genericParameterType instanceof ParameterizedType) {
                ParameterizedType aType = (ParameterizedType) genericParameterType;
                Type[] parameterArgTypes = aType.getActualTypeArguments();
                for (Type parameterArgType : parameterArgTypes) {
                    Class parameterArgClass = (Class) parameterArgType;
                    System.out.println("parameterArgClass = "
                            + parameterArgClass);
                }
            }
        }
    }
}

Output: parameterArgClass = class java.lang.String

It was possible because your explicitly declared in source code that List can contains only Strings. However in case

public <T> void foo2(List<T> s){
      //reflect s somehow to get T
}

T can be anything so because of type erasure it is impossible to retrieve info about precise T class.

Pshemo
  • 122,468
  • 25
  • 185
  • 269