简体   繁体   English

运行时局部变量的通用类型

[英]Generic type of local variable at runtime

Is there a way in Java to reflect a generic type of a local variable? Java中有没有办法反映局部变量的通用类型? I know you sould to that with a field - Get generic type of java.util.List . 我知道您可以通过一个字段来解决这个问题- 获取泛型类型的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
}

No . 不行 Due to Java's Type Erasure , all generics are stripped during the compile process. 由于Java的Type Erasure ,在编译过程中会删除所有泛型。

You can however use instanceOf or getClass on elements in the list to see if they match a specific type. 但是,您可以对列表中的元素使用instanceOfgetClass来查看它们是否与特定类型匹配。

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 例如从firs foo方法获取String

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 输出: parameterArgClass =类java.lang.String

It was possible because your explicitly declared in source code that List can contains only Strings. 可能是因为您在源代码中明确声明List只能包含字符串。 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. T可以是任何东西,因此由于类型擦除,不可能检索有关精确T类的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM