简体   繁体   English

使用反射访问类型参数

[英]Accessing Type Parameters Using Reflection

How do I find type parameter values passed to a super class using reflection? 如何查找使用反射传递给超类的类型参数值?

For example, given Bar.class , how do I find that it passes Integer.class to Foo 's type parameter T ? 例如,给定Bar.class ,我如何发现它将Integer.class传递给Foo的类型参数T

public class Foo<T> {
}

public class Bar extends Foo<Integer> {
}

Thanks! 谢谢!

public class Bar extends Foo<Integer> {

 public Class getTypeClass {
   ParameterizedType parameterizedType =
     (ParameterizedType) getClass().getGenericSuperClass();
  return (Class) parameterizedtype.getActualTypeArguments()[0];
 }

}

The given above should work in most of the practical situations, but not guaranteed , because of type erasure, there is no way to do this directly. 上面给出的应该在大多数实际情况下都可以工作, 但是由于类型擦除,因此不能保证能直接执行此操作。

You can try 你可以试试

ParameterizedType type = (ParameterizedType) Bar.class.getGenericSuperclass();
System.out.println(type.getRawType()); // prints; class Foo
Type[] actualTypeArguments = type.getActualTypeArguments();
System.out.println(actualTypeArguments[0]); // prints; class java.lang.Integer

This only works because Bar is a class which extends a specific Foo. 这仅适用,因为Bar是扩展特定Foo的类。 If you declared a variable like the following, you wouldn't be able to determine the parameter type of intFoo at runtime. 如果声明了类似以下的变量,则将无法在运行时确定intFoo的参数类型。

Foo<Integer> intFoo = new Foo<Integer>();

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

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