2

Java中有没有办法反映局部变量的泛型类型?我知道你会用一个字段来解决这个问题 -获取 java.util.List 的泛型类型。任何想法如何解决,例如:

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

或者更笼统:

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

2 回答 2

7

没有。由于 Java 的Type Erasure,所有泛型在编译过程中都会被剥离。

但是,您可以在列表中的元素上使用instanceOfgetClass来查看它们是否与特定类型匹配。

于 2012-08-03T15:42:35.777 回答
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.

于 2012-08-03T15:52:02.903 回答