Generic type of local variable at runtime

前端 未结 2 1048
忘掉有多难
忘掉有多难 2020-12-06 23:33

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

相关标签:
2条回答
  • 2020-12-07 00:16

    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.

    0 讨论(0)
  • 2020-12-07 00:19

    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.

    0 讨论(0)
提交回复
热议问题